import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; public class SocketExample { public static void main(String[] args) throws Exception { // Outgoing socket to www.dnorth.net port 80 originating from a specified IP on the local machine Socket socket = new Socket(); // specify outgoing address InetAddress outgoingAddress = Inet4Address.getByName("10.0.0.158"); socket.bind(new InetSocketAddress(outgoingAddress, 0)); // 0 means randomly pick source port // make connection socket.connect(new InetSocketAddress(Inet4Address.getByName("www.dnorth.net"), 80)); } }