specifying source and destination port on socket - java

I am creating a socket for TCP communication and would like to know how to specify a source port.
Socket socket = new Socket();
socket.connect(dstAddress);

After creating your new socket, call bind() with the local port number you want to use, then connect to the remote host.
#EJP is correct, though. Don't do this lightly since you can end up not being able to create the socket if something else happens to be using that port or even if your program has recently used it and closed it.
If it's not working, you may need to look at the library you're using.

Socket has multiple constructors. Try this one

You have to use InetSocketAddress, declared in the package java.net. The easiest way to use it is:
InetSocketAddress(host, port)), something like this:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("http://myserver.com", 80));
Which connect to the web server listening on the port 80 in myserver.com.

Related

TCP socket connection over internet

I am doing a project for which connection between server and client is required.
I did it by adding TCP sockets.
Here is the code fraction :
Server:
ServerSocket welcomeSocket = new ServerSocket(80);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
WorkerThread wt = new WorkerThread(connectionSocket, id);
Thread t = new Thread(wt);
t.start();
workerThreadCount++;
}
Client :
Socket skt = new Socket("192.168.0.108", 80); // The IP address is from cmd->ipconfig/all-> IPv4 Address
outToServer = new PrintWriter(skt.getOutputStream(), true);
inFromServer = new BufferedReader(new InputStreamReader(skt.getInputStream()));
It all works when both ends are in same device/under same WiFi.But I don't understand what to do for creating connection over internet.
Please help with clear steps.
Here:
Socket skt = new Socket("192.168.0.108", 80);
That is local address. If you want to have a server that is reachable on the internet, then that server needs to have its global public IP address!
In other words: you have to make sure that the server can be reached from the internet somehow. For example by turning to some service provider that hosts servers that you can then equip with your code!
The whole purpose of 192.168 addresses is to be defined only in a local subnet.
Alternatively, you have to check if your ISP has a service where the ISP assigns an IP address to your connection, and that allows calls from the internet to go to your "place".
Meaning: when you want to receive phone calls, you need a phone that is connected to the phone net!
In order to connect to a socket over WAN, you must port forward that port to your local device. This can be done in your routers' settings.
192.168.0.108 --> That's your local IP-address.
This can be used on your local network without any requirements for port forwarding whatsoever. However, to use it over WAN, execute the following steps:
Step 1: Search for your routers' model number and port forwarding on Google on how-to forward port 80 to your local IP-address. Warning: use a static IP-address on your local device to prevent your IP from changing after a reboot.
Step 2: Go to a website like IP Chicken and find your external IP-address.
You can then connect to your socket using:
Socket skt = new Socket("[EXTERNALIP]", 80);
Please be noticed: unless you have a business network, your external IP-address will probably change from time to time.

Why and how am i supposed to use socket.accept() in python?

This accept() method return a tuple with a new socket and an address but why do i need a new socket if i already have one, so why don't use it?
import socket
sock = socket.socket()
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
print 'connected:', addr
while True:
data = conn.recv(1024)
if not data:
break
conn.send(data.upper())
conn.close()
ps: When i program sockets in Java, i don't really have this kind of accepting stuff and i only need one socket per client and one per server, which makes sense.
You have one listening socket active while the server is running and one new connected socket for each accepted connection which is active until the connection is closed.
Seems like you haven't implemented TCP in Java before.
The example you are providing with, uses a default AF_INET and SOCK_STREAM which by default is TCP:
socket.socket([family[, type[, proto]]])
Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6 or AF_UNIX. The socket type should be SOCK_STREAM (the default), SOCK_DGRAM or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted in that case.
If you were implemented SOCK_DGRAM which is UDP, you wouldn't need to be using sock.accept()

Receiving UDP data in Java

I'm trying to receive UDP data broadcast by PlayCap to network address 192.168.103.255 port 3000 in Java, but I'm having trouble setting things up. Here's what I have:
DatagramSocket socket = new DatagramSocket();
InetSocketAddress address = new InetSocketAddress("192.168.103.255", 3000);
socket.bind(address);
I'm getting "java.net.SocketException: already bound" from the bind call. I'm pretty inexperienced with networking, so I may be doing something way wrong here. Any help is appreciated.
Here is the stacktrace:
java.net.SocketException: already bound
at java.net.DatagramSocket.bind(Unknown Source)
at runner.main(runner.java:16)
I dont want to revive and old thread but i don't think the answer to this question is correct. I faced the same issue when i used the similar code to create a DatagramSocket.
DatagramSocket socket = new DatagramSocket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(InetAddress.getByName("localhost"), 5566));
This results in a SocketException
Exception in thread "main" java.net.SocketException: already bound
at java.net.DatagramSocket.bind(DatagramSocket.java:376)
at testapplication.TestApplication.main(TestApplication.java:25)
Java Result: 1
Not because there is another process occupying the same port but i have created an already BOUND datagram socket when i use the default constructor.
new DatagramSocket()
According to javadoc:
DatagramSocket()
Constructs a datagram socket and binds it to any available port on the
local host machine.
So the reason for the exception is you are trying to bind an already bound socket. To make it work you need to create an unbond socket with below constructor
DatagramSocket socket = new DatagramSocket(null);
InetSocketAddress address = new InetSocketAddress("192.168.103.255", 3000);
socket.bind(address);
Hope this helps...
Do netstat -a -o -n and from this you can find that either this port is already bind or not(even from this you can get all the bound ports).If yes , then try any other port :)
Most probably your application is running twice. Or you might be executing the same code twice. Even the same application may fail when binding twice.
Happens a lot for beginners that they didn't shut down their previous attempt (happened to me, too), and then their port is already in use. Make sure to add proper exception handling, e.g. by popping up a message "Port already in use."
Note that for listening you usually will bind a port only, without an explicit address (you might need to use "0.0.0.0" for this). Then you can receive both broadcast and unicast.
The code I use for listening to broadcasts is simply:
DatagramSocket s = new DatagramSocket();
s.bind(new InetSocketAddress(port))
Note that I'm not binding to a particular address, but only to a port.
Check the port 3000 it may be already used by another application. Try using a different port.

Bind an interface in java TCP connection

I have two interfaces in a solaris host. I would like to initiate two TCP connections to a single TCP server via both interfaces as shown in the diagram. Are there any options in Java to bind the interface to the TCP socket to override the local routing table?
I am attaching the network diagram,
I would like to use both the serial links bandwidth to get the data from server. Hence I would like to initiate the connection on both the interfaces.
thanks,
You can use
Socket s = new Socket(hostname, port, localInterface, 0);
However, many OSes do not honour this "hint" and will use the routing table anyway.
Do you mean something like this:
Socket socket1 = new Socket();
socket1.bind(new InetSocketAddress("10.1.1.1", port));
socket1.connect(new InetSocketAddress("10.1.3.1", port));
Socket socket2 = new Socket();
socket2.bind(new InetSocketAddress("10.1.2.1", port));
socket2.connect(new InetSocketAddress("10.1.3.1", port);

Communiation with multiple clients via Sockets

I have a Server Socket and 3-4 android devices as clients. I'm using TCP/IP for communications. Which is the best method. Should I use multiple ports for each client? Or should I use same port. If using same function then how should I identify the communication addressed to different devices?
No, you do not need several ports.
ServerSocket server = new ServerSocket(port);
while (true)
{
Socket socket = server.accept();
// do something with this socket - aka 1 client
new SomeClientClass(socket);
InputStream in = socket.getInputStream();
in.read(byte[]);
OutputStream out = socket.getOutputStream;
// out will only write response to its own client.
// when this new SomeClientClassis created, method returns to this point
// in while loop and waits for the next client
}
You can use one port. The client can send you its id. If it can't you can look at the clients IP address to workout which one it is.
There are thousands of TCP client/server code examples on the web, but I would start with the sample code which comes with the JDK,

Categories

Resources