Get local IP address for socket - c#

I'm looking to get the local IP address of the socket I just created. I need to be able to support a server with more than one NIC and communicate back to the requesting client what the direct IP address is to connect later on. I'm using for following code:
Socket rsock = null;
rsock= new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
rsock.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
rsock.Bind(new IPEndPoint(IPAddress.IPv6Any, port));
rsock.Listen((int)SocketOptionName.MaxConnections);
After this point, .LocalEndPoint kicks out: [::]:PORT.
Background:
The reason I need the IP address is that a secondary connection by another client will need to return to this specific server. These servers will likely be behind a load balancer for the initial server selection so the client cannot resolve the IP address based on the host name.

Since you're binding to IPAddress.IPv6Any, the endpoint information will not be available before the first I/O operation occurs. The documentation says:
If you allow the system to assign your socket's local IP address and
port number, the LocalEndPoint property will be set after the first
I/O operation. For connection-oriented protocols, the first I/O
operation would be a call to the Connect or Accept method.
So, in your case, you will have to call Accept() before accessing LocalEndPoint in order to obtain meaningful information.

Related

The requested address is not valid in its context when I try to listen a port

I am trying to connect to a sensor using network, the sensor's ip is 192.168.2.44 on port 3000;
My Code:
byte[] byteReadStream = null; // holds the data in byte buffer
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("192.168.2.44"), 3000);//listen on all local addresses and 8888 port
TcpListener tcpl = new TcpListener(ipe);
while (true)
{
//infinite loop
tcpl.Start(); // block application until data and connection
TcpClient tcpc = tcpl.AcceptTcpClient();
byteReadStream = new byte[tcpc.Available]; //allocate space
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
Console.WriteLine(Encoding.Default.GetString(byteReadStream) + "\n");
}
But when I run this code, I get this error:
The requested address is not valid in its context
Use IPAddress.Any to listen. This seems to be your goal:
//listen on all local addresses
The listening address you have specified is invalid for some reason. There is no need to specify a numeric address.
The TcpListener listens for connections from TCP network client, on a given port on your local machine. That is, for incoming connections. Your code will be acting as a "server" of sorts.
The requested address is not valid in its context
Simply, it means that the IP address given is not used by any network interface on your machine.
Use IPAddress.Any to listen on any IP address (i.e. network interface).
However, it might be the case that you need to connect to the sensor (on port 3000), not the other way around.
EDIT: The new exception just tells you that you have two applications trying to listen to the same interface/port combination. Do you have two instances running at the same time?
One of the reason for this issue could be the presence of defaultProxy section in the configuration file which would be routing every outgoing call via proxy address mentioned in this setting. Ensure that either there is a proxy server/service listening at the proxy address, or comment this section to stop the routing. In case the application configuration file does not have it, and this error is still there, check for the defaultProxy section in the machine.config file. machine.config should be available in folder C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config. In our case it was the defaultProxy in machine.config.

How to send request from different static IP address to a any website?

I am sending HTTP request using C#. (http://codesamplez.com/programming/http-request-c-sharp)
I have dedicated server on.I have purchased more static IPs.
How can I send request using these different IPs.
What you want to do is bind to a specific network adapter. By default the LocalEndpoint is null so your connection will be to assigned an adapter. You can specify what to bind to using HttpWebRequest.ServicePoint.BindIPEndPointDelegate.
var req = (HttpWebRequest)WebRequest.Create("http://google.com/");
req.ServicePoint.BindIPEndPointDelegate = BindTo;
using (req.GetResponse());
static IPEndPoint BindTo(ServicePoint servicepoint, IPEndPoint remoteendpoint, int retrycount)
{
IPAddress ip = IPAddress.Any; //This is where you specify the network adapter's address
int port = 0; //This in most cases should stay 0. This when 0 will bind to any port available.
return new IPEndPoint(ip, port);
}
Here is some more information on binding from msdn.
Use the Bind method if you need to use a specific local endpoint. You
must call Bind before you can call the Listen method. You do not need
to call Bind before using the Connect method unless you need to use a
specific local endpoint. You can use the Bind method on both
connectionless and connection-oriented protocols.
Before calling Bind, you must first create the local IPEndPoint from
which you intend to communicate data. If you do not care which local
address is assigned, you can create an IPEndPoint using IPAddress.Any
as the address parameter, and the underlying service provider will
assign the most appropriate network address. This might help simplify
your application if you have multiple network interfaces. If you do
not care which local port is used, you can create an IPEndPoint using
0 for the port number. In this case, the service provider will assign
an available port number between 1024 and 5000.
If you use the above approach, you can discover what local network
address and port number has been assigned by calling the
LocalEndPoint. If you are using a connection-oriented protocol,
LocalEndPoint will not return the locally assigned network address
until after you have made a call to the Connect or EndConnect method.
If you are using a connectionless protocol, you will not have access
to this information until you have completed a send or receive.

Udpclient localendpoint, remoteendpoint. What is that mean?

How can i specify specific ipaddress:port for udpclient to receive? im confused with updclient.client.localendpoint and udpclient.client.remoteendpoint. i was thinking maybe its remoteendpoint, but i cannot display remoteendpoint value. plus my local endpoint ip is 0.0.0.0. what is that mean?
0.0.0.0 means "any address". The local endpoint is the IP address and port you will listen for packets on. The remote endpoint is not required for UdpClient objects. It only specifies the default host to send a packet to, if you do not specify one when sending the packet.
You can leave the local endpoint as 0.0.0.0 if you want to listen for traffic on all of your assigned IP addresses on all of your network connections. You only need to change this if you only want to listen on one particular address/connection.

How to Get IP Address of Server responding to WebResponse C#

I am trying to find the ip address (not the hostname) that responded to my WebRequest in C#. I do not want to do a DNS resolution, because their are cases where the DNS records returned are not the servers responding to the request. For ex:
Client -> Load Balancer -> Web Server
The DNS server would respond with the Load Balancer's IP. Assuming the responding Web server is not going back through the Load Balancer, the IP address would then be the actual Web server which is what I am trying to find.
Do you have access to the server side code? Or to the web server configuration? You could always place the machines IP, or whatever identifier you'd like, in a custom header and look for that on the client.
As for your original question, I do not believe that information is exposed anywhere by the HttpWebRequest/HttpWebResponse classes.
I think you'll have to go OSI-dipping, and create and harness your own socket;
then you'll have access to the RemoteEndPoint property (at least after your socket has connected, or been connected to) like so :
Socket sprocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sprocket.Connect("www.google.com", 80);
string IPAddressOfRespondingServer = ((IPEndPoint)sprocket.RemoteEndPoint).Address.ToString();

Find Out Connected clients IP's?

How to find out Connected Clients Ip Address. And how we can store that address to an array of datatype IPAddress?
Check the RemoteEndPoint of your socket:
If you are using a connection-oriented
protocol, the RemoteEndPoint property
gets the EndPoint that contains the
remote IP address and port number to
which the Socket is connected. If you
are using a connectionless protocol,
RemoteEndPoint contains the default
remote IP address and port number with
which the Socket will communicate. You
must cast this EndPoint to an
IPEndPoint before retrieving any
information. You can then call the
IPEndPoint.Address method to retrieve
the remote IPAddress, and the
IPEndPoint.Port method to retrieve the
remote port number.
If you use higher level components like TcpListener and TcpClient then you can access the underlying socket and retrieve the remote end point.
If you use other technologies like ASP.Net, WCF or Remoting then you must say so in your post.
To store an IPAddress you retrieve the underlying bytes using IPAddress.GetAddressBytes. You reconstruct the address from the bytes using the byte[] constructor.
Are we in Windows? Do you need to use this information inside an application or a console command could do the trick?
maybe you could try with netstat -na in a shell.

Categories