Find Static IP in C#

Talk2Tom11

Well-known member
Joined
Feb 22, 2004
Messages
144
Location
Westchester, NY
I am writing a client/server application. In the server part it looks up for an IP address. The only problem is that it looks for the local IP. Which with a local IP, if a user wants to access the server froma client that is not within that network then it will not be able to log in. I have inserted the code below that I used to find the IP for the server, but for the local IP. If anyone knows how to find the Static IP please post. :)


Code:
// Determine the IPAddress of this machine
			IPAddress [] aryLocalAddr = null;
			String strHostName = "";
			try
			{
				// NOTE: DNS lookups are nice and all but quite time consuming.
				strHostName = Dns.GetHostName();
				IPHostEntry ipEntry = Dns.GetHostByName( strHostName );
				aryLocalAddr = ipEntry.AddressList;
			}
			catch( Exception ex )
			{
				Console.WriteLine ("Error trying to get local address {0} ", ex.Message );
			}
	
			// Verify we got an IP address. Tell the user if we did
			if( aryLocalAddr == null || aryLocalAddr.Length < 1 )
			{
				Console.WriteLine( "Unable to get local address" );
				return;
			}
			Console.WriteLine( "Listening on : [{0}] {1}:{2}", strHostName, aryLocalAddr[0], nPortListen );
			
			// Create the listener socket in this machines IP address
			Socket listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			listener.Bind( new IPEndPoint( aryLocalAddr[0], 399 ) );
			//listener.Bind( new IPEndPoint( IPAddress.Loopback, 399 ) );	// For use with localhost 127.0.0.1
			listener.Listen( 10 );
 
Assuming that by "local IP" you mean the IP address assigned to the computer by NAT or the one specified manually in the TCP/IP configuration dialog, and by "static IP" you mean the IP address of the gateway (router), you cant retrieve the "static IP" without issuing a network request, nor should you have to. Most routers allow for port forwarding, which will easily deal with issues such as this.
 
umm... ok. I kind of understand what you are saying. I am not all to familiar with this stuff, but how would I get my server to look for that other IP and then listen on it
 
As long as the client knows the static IP of the server he can connect to it on port 399 ( in yer case) your existing server code should work just fine.

You can access www.whatsmyip.org from a browser on the machine thats gonna host the server to get the static IP of the machine [ im sure there are easier methods butthis is the one that im aware of ]

the above code snipit just ensures that the machine running has an IP, and then uses that address to bind a socket and listen for requests.


ther real work happens after you call accept
ie

Socket requestHandler = listener.Accept();
 
Back
Top