2009-12-14 20 views
31

Come si determina l'indirizzo IP remoto di una presa collegata?Come ottenere l'indirizzo IP di un endpoint socket remoto

Possiedo un oggetto RemoteEndPoint a cui posso accedere e che è anche membro AddressFamily.

Come utilizzarli per trovare l'indirizzo IP?

Grazie!

attualmente cercando

IPAddress.Parse(testSocket.Address.Address.ToString()).ToString(); 

e ottenere 1.0.0.127 invece di 127.0.0.1 per i punti finali localhost. È normale?

risposta

56

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx

È quindi possibile chiamare l'IPEndPoint .. ::. Metodo Indirizzo per recuperare l'IPAddress a distanza, e l'IPEndPoint .. ::. Metodo porta per recuperare il numero di porta remota.

più dalla maglia (sistemato un sacco eh):

Socket s; 

IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint; 
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint; 

if (remoteIpEndPoint != null) 
{ 
    // Using the RemoteEndPoint property. 
    Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port); 
} 

if (localIpEndPoint != null) 
{ 
    // Using the LocalEndPoint property. 
    Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port); 
} 
5

RemoteEndPoint è una proprietà, il suo tipo è System.Net.EndPoint che eredita da System.Net.IPEndPoint.

Se dai un'occhiata a IPEndPoint members, vedrai che c'è una proprietà Address.

+1

Tutto ciò che vedo disponibile per i membri di RemoteEndPoint è AddressFamily. Come posso accedere a Indirizzo? – bobber205

+1

((System.Net.IPEndPoint) socket.RemoteEndPoint) .Address –

+0

Grazie! :) Sto provando string remoteIP = IPAddress.Parse (testSocket.Address.Address.ToString()) .ToString(); e ottenere "1.0.0.127" anziché "127.0.0.1" per le connessioni localhost. È normale? – bobber205

2
string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString(); 
0

Ho creato questo codice in VB.NET ma è possibile tradurre. Bene finta avete la client variabile come TcpClient

Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":")) 

Speranza che aiuta! Saluti.

Problemi correlati