Shantanu Gupta
Shantanu Gupta

Reputation: 21108

How to get an IP address from Socket

I am trying to get an ip address that is bound to receiveSock. How can i get it.

Ques 1:

ipEndReceive = new IPEndPoint(IPAddress.Any, receivePort);
receiveSock = new Socket(AddressFamily.InterNetwork
                        , SocketType.Stream, ProtocolType.Tcp);

receiveSock.Bind(ipEndReceive);

When code reaches Bind function. An error occurs

Invalid Argument, Error Code: 10022, Message : An invalid argument was supplied

Ques 2:

ipEndReceive = new IPEndPoint(IPAddress.Parse("127.0.0.1"), receivePort);
receiveSock = new Socket(AddressFamily.InterNetwork
                        , SocketType.Stream, ProtocolType.Tcp);                   
receiveSock.Bind(ipEndReceive);

ErrorLog.WritetoErrorlog("\nRemote IP Address : " + ((IPEndPoint)receiveSock.RemoteEndPoint).Address.ToString()

When I tries with this Ip. It shows me the same error as above

Upvotes: 3

Views: 5914

Answers (1)

John Leidegren
John Leidegren

Reputation: 61057

First, it looks like it's the local end point you want. Secondly when you specify IPAddress.Any (0.0.0.0) you explicitly state that the Socket is to be bound to no particular interface. Each IP adress matches exactly one interface.

var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, somePort));
Trace.WriteLine(s.LocalEndPoint); // should be what you're looking for

The socket is bound and will be used for receiving connections. It doesn't have a RemoteEndPoint. This should be abundantly clear becuase the Accept method returns a new Socket object that represents the connection between two end points (local/remote).

Note: that this is an IPv4 socket (AddressFamily.InterNetwork) so don't try and bind it to anything else.

Check out the docs on MSDN, you can learn more about typical Winsock programming (as the Socket class is just a Winsock wrapper) there.

Upvotes: 1

Related Questions