I am writing a Java application that opens a Socket
, as follows:
socketConnection = new Socket();
socketConnection.connect(new InetSocketAddress(server, port));
and occasionally performs operations such as reads and writes. One function that is important for sending meta data along with packets is the local and remote addresses of the connection. For example, I am getting the local address bytes as:
public byte[] getLocalIP() {
InetAddress localAddr = socketConnection.getLocalAddress();
byte[] addressBytes = localAddr.getAddress();
return addressBytes;
}
My protocol would like to have the IPv4 of the sender sent along in the header. However, sometimes this function returns 16 bytes instead of 4, which causes problems. Even more confusing, the behavior sometimes changes within the same run of the program, despite the same Socket object returning IPv4 for previous calls. It is difficult to replicate, I'm still not sure under what circumstances it happens.
Under what circumstances will the above return an IPv6 instead of an IPv4? Is this dependent on the network I'm running on? And what would cause it to shift during the middle of a program execution?