Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get client IP using socket programming c#

Tags:

c#

sockets

Is there anyone who knows how to get client IP address using socket programming while we are requesting the access of file transferring?? I am using C#.

like image 325
Emaad Ali Avatar asked Jul 23 '10 13:07

Emaad Ali


People also ask

Do sockets have IP addresses?

A socket consists of the IP address of a system and the port number of a program within the system. The IP address corresponds to the system and the port number corresponds to the program where the data needs to be sent: Sockets can be classified into three categories: stream, datagram, and raw socket.

What is IP address in socket programming?

IP is an addressing and fragmentation protocol. It breaks all communications into packets, chunks of data up to 65536 bytes long. Packets are individually routed from source to destination. IP is allowed to drop packets; i.e., it is an unreliable protocol.


2 Answers

In order to get the actual IP address:

// Using the RemoteEndPoint property.
Console.WriteLine (
"I am connected to " + IPAddress.Parse (((IPEndPoint)s.RemoteEndPoint).Address.ToString ()) + 
"on port number " + ((IPEndPoint)s.RemoteEndPoint).Port.ToString ());

// Using the LocalEndPoint property.
Console.WriteLine (
"My local IpAddress is :" + IPAddress.Parse (((IPEndPoint)s.LocalEndPoint).Address.ToString ()) +
"I am connected on port number " + ((IPEndPoint)s.LocalEndPoint).Port.ToString ());

taken from the msdn site:

like image 163
Zapnologica Avatar answered Sep 29 '22 01:09

Zapnologica


Socket.LocalEndPoint or Socket.RemoteEndPoint should do the trick, depending on whether you're the client or not.

like image 20
Stephen Cleary Avatar answered Sep 29 '22 01:09

Stephen Cleary