views:

70

answers:

1

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

A: 

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.

John Leidegren
@John: Thx for explanation. Could u put some light on your first three lines. I m not sure what you are trying to explain. **Socket is to be bound to no particular interface** What does `interface` represents here
Shantanu Gupta
interface referes to a specific component in the network stack. your computer can be connected to the internet (or local network) in many ways. you can have several connections (wired and wireless). each active interface represents such a connection and has a distinct IP address. When you type `netsh interface ipv4 show addresses` you get a list of all currently installed network interfaces. One such interface is the loopback interface which has the static IP address `127.0.0.1`. When I say no particular interface, I mean that a connection may be made on any interface.
John Leidegren
If you computer is a gateway or firewall, you can restrict access from either side of the network, by allowing connections only on specific interfaces. I believe this relates more to network segementation than your original question though.
John Leidegren