Suppose I have a simple winsock server that has a listening socket, and then when a connection is accepted, it stores the socket in an array of sockets (to allow multiple connections).
How can I get the IP address of a specific connection? Is it stored in the socket handle?
As long, as the socket stays connected, you can get both own socket address and peer one.
getsockname will give you local name (i.e. from your side of a pipe)
getpeername will give you peer name (i.e. distant side of a pipe)
This information is available only when the socket is opened/connected, so it is good to to store it somewhere if it can be used after peer disconnects.
Yes it is stored in the socketaddr_in struct, you can extract it using:
SOCKADDR_IN client_info = {0};
int addrsize = sizeof(client_info);
// get it during the accept call
SOCKET client_sock = accept(serv, (struct sockaddr*)&client_info, &addrsize);
// or get it from the socket itself at any time
getpeername(client_sock, &client_info, sizeof(client_info));
char *ip = inet_ntoa(client_info.sin_addr);
printf("%s", ip);
Related
I'm using lib winsock2 in Visual Studio community, using simple client example.
After executing connect() function, would like to know how can I get/return self/source port number of open connection.
In winsock2, when a connection is established you can bind socket port to some specific port you want to use. For example, let´s say you are creating an UDP or TCP socket and you want that a specific local port is used. In that case you can do that by calling bind function ( https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-bind )
if (port != 0) {
int rv = -1;
struct sockaddr_in recv_addr;
ZeroMemory(&recv_addr, sizeof(struct sockaddr_in));
recv_addr.sin_family = AF_INET;
recv_addr.sin_port = htons(port);
recv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
rv = bind(udp_channel->socket, (SOCKADDR *)& recv_addr, sizeof(recv_addr));
}
This is the same bind function you will use to set listening port when your socket will act as a server in UDP or TCP, it's the same.
In case you don't do socket binding, socket port will be assigned on connection. There seems to be the function getsockname that user207421 mentioned.
getsockname() or getpeername()
returning Structured data with short sin_family and char sa_data[] with different amount of data depending on the protocols used
after connection to server use fuction getsockname() or getpeername() to get the structured data we need to extract the data to get the port
you use function ntohs() for extracting the port data with macro function SS_PORT to convert struct to sockaddr_in
example:
sockaddr struc_;
int struc_len = sizeof(struc_);
/* connect function*/
getsockname(ConnectSocket, (LPSOCKADDR)&struc_, &struc_len);
int port_int_ = ntohs(SS_PORT(&struc_));
or you can define a ready-made structure / create your own, with a pointer to port number data.
I'm looking at the udp client example here:
http://www.linuxhowtos.org/data/6/client_udp.c
snippet:
/* UDP client in the internet domain */
struct sockaddr_in server, from;
//...snipped
sock= socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) error("socket");
server.sin_family = AF_INET;
hp = gethostbyname(argv[1]);
if (hp==0) error("Unknown host");
bcopy((char *)hp->h_addr,
(char *)&server.sin_addr,
hp->h_length);
server.sin_port = htons(atoi(argv[2]));
length=sizeof(struct sockaddr_in);
//... snipped
n=sendto(sock,buffer,
strlen(buffer),0,(const struct sockaddr *)&server,length);
if (n < 0) error("Sendto");
n = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length);
if (n < 0) error("recvfrom");
//... snipped
I'm trying to understand how it knows where to receive the message from. I know when sendto is called an available port is chosen and that is embedded in the udp message and the server application can read that and reply to it. How does the client code know to receive a message on that port?
This answer: https://stackoverflow.com/a/48245273/2748602 indicates there is kind of an implicit bind when the sendto function is called. How does it work? Is it in fact a bind with a random available port number that is as permanent as if I had called bind or something else? It seems there's some aspect of permanence. Just interested in a little more detail.
There is an implicit bind if the socket is unbound since all packets have to carry both a source port. So the API assumes that if you didn't care enough about the port to bind your socket beforehand, then it can just bind the socket to a random port. And while unfortunately I don't know the implementation details of sendto, I can offer some official documentation.
For Linux, from the udp man page:
When a UDP socket is created, its local and remote addresses are
unspecified. Datagrams can be sent immediately using sendto(2) or
sendmsg(2) with a valid destination address as an argument. When
connect(2) is called on the socket, the default destination
address is set and datagrams can now be sent using send(2) or write(2)
without specifying a destination address. It is still possible to
send to other destinations by passing an address to sendto(2) or
sendmsg(2). In order to receive packets, the socket can be bound to a
local address first by using bind(2). *Otherwise, the socket layer
will automatically assign a free local port out of the range defined
by /proc/sys/net/ipv4/ip_local_port_range and bind the socket to
INADDR_ANY.
For Windows, a snippet from the documentation for Winsock 2's sendto:
If the socket is unbound, unique values are assigned to the local
association by the system, and the socket is then marked as bound. If
the socket is connected, the getsockname function can be used to
determine the local IP address and port associated with the socket.
... there is kind of an implicit bind when the sendto function is called. How does it work? Is it in fact a bind with a random available port number that is as permanent as if I had called bind or something else?
man ip(7):
ip_local_port_range (since Linux 2.2)
This file contains two integers that define the default local
port range allocated to sockets that are not explicitly bound
to a port number—that is, the range used for ephemeral ports.
An ephemeral port is allocated to a socket in the following
circumstances:
* the port number in a socket address is specified as 0 when calling bind(2);
* listen(2) is called on a stream socket that was not previously bound;
* connect(2) was called on a socket that was not previously bound;
* sendto(2) is called on a datagram socket that was not previously bound.
I am writing a UDP client/server application. The server is a broadcast server, that broadcasts on a particular port to two clients on the same subnet. Each client receives a datagram and sends a response to the server. Each client knows the ip address of the server in advance.
My client is basically as in the client example of http://man7.org/linux/man-pages/man3/getaddrinfo.3.html, i.e. it uses the connect() function to specify the endpoint of all outgoing packets. By using connected UDP, the client can use read() and write() to the socket file descriptor rather than sendto/recvfrom.
For my server, I want to adopt a similar approach - configure the socket for broadcasting, and call read/write on the file descriptor. I can bind() the socket to listen for incoming datagrams on the specified port, and these are collected fine.
Minus error checking, my server code looks like this:
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
int broadcast = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof int);
struct sockaddr_in servaddr;
memset((char*) &servaddr, 0, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
int success = bind(sockfd, (struct sockaddr*) &servaddr, sizeof servaddr);
int BUFSIZE = 256;
char buf[BUFSIZE];
while (1)
{
// this works fine
int bytes_read = read(sockfd, buf, BUFSIZE);
// WANT TO BROADCAST HERE
int bytes_written = write(sockfd, buf, bytes_read);
}
However, when I try and broadcast a packet in the write() line, I get a 'Destination address not specified' error. I could call connect() to set the destination address, but I don't think connect() works on a broadcast socket.
Is there a way of broadcasting using write() rather than sendto?
The problem with using connect() for broadcast is that (in addition to modifying the behavior of send()/write()), connect() will install a filter on the socket so that it only receives packets whose source-IP field matches the IP address specified in the argument to connect().
That means if you call connect() on your socket with a broadcast-address as its argument, then your socket will only receive packets coming from that broadcast-address -- but packets are never (AFAIK) tagged as coming from a broadcast address -- rather, their Source-IP field is set to the IP address of the computer that sent the packet, as usual. The upshot is that if you connect() your socket to a broadcast address, you won't receive any packets on that socket.
I'm in the process of writing a project for college involving writing a chat client and server using POSIX sockets and C++.
The clients are supposed to converse with each other using P2P, such as each client has his own open UDP socket through which he sends and recieves messages from/to other clients.
My problem is 2-fold:
My UDPSocket class constructor seems to be ignoring the port number completely, binding to port 65535 regardless of the parameter.
The port is binding to IP 255.255.255.255 rather than my own IP (10.0.0.3), or at least that's what i get when I call getpeername.
To the best of my knowledge passing INADDR_ANY should bind to my local address, and passing port number 0 should make the OS choose a free port, what am I doing wrong?
This is the constructor of my UDPSocket class:
UDPSocket::UDPSocket(int port){
socket_fd = socket (AF_INET, SOCK_DGRAM, 0);
// clear the s_in struct
bzero((char *) &in, sizeof(in)); /* They say you must do this */
//sets the sin address
in.sin_family = (short)AF_INET;
in.sin_addr.s_addr = htonl(INADDR_ANY); /* WILDCARD */
in.sin_port = htons((u_short)port);
fsize = sizeof(from);
//bind the socket on the specified address
if(bind(socket_fd, (struct sockaddr *)&in, sizeof(in))<0){
perror ("Error naming channel");
}
}
This is the initialization:
m_Socket = new UDPSocket(0);
And this is the method I use to retrieve the binded address: (UDPSocket inherits Socket)
std::string Socket::GetSocketAddress()
{
struct sockaddr_in addr;
int len = sizeof(addr);
getpeername(socket_fd, (struct sockaddr*)&addr, (socklen_t*)&len);
char ipAddressBuffer[50];
memset(ipAddressBuffer, 0, sizeof(ipAddressBuffer));
sprintf(ipAddressBuffer, "%s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
return ipAddressBuffer;
}
Any help would be greatly appreciated,
Avi.
You're using getpeername , which gives you the remote address of a connected socket. If you check the return value of getpeername(), it should indicate failure.
You need to use getsockname() instead of getpeername() to get the address of your local socket
You need to check that getsockname() succeeds.
Note that your socket is bound to the special 0.0.0.0 address, which means "all local interfaces", so that's what getsockname() will also return.
Answering the more general question "How to set up peer-to-peer communications with UDP":
With UDP sockets, while you can use connect, you generally don't want to, as that restricts you to a single peer per socket. Instead, you want to use a single unconnected UDP socket in each peer with the sendto and recvfrom system calls to send and receive packets with a different address for each packet.
The sendto function takes a packet and a peer address to send it to, while the recvfrom function returns a packet and the peer address it came from. With a single socket, there's no need to multiplexing with select or poll -- you just call recvfrom to get the next packet from any source. When you get a packet, you also get the peer address to send packets (back) to.
On startup, your peer will create a single socket and bind it to INADDR_ANY (allowing it to receive packets on any interface or broadcast address on the machine) and either the specific port assigned to you program or port 0 (allowing the OS to pick any unused port). In the latter case, you'll need to use getsockname to get the port and report it to the user. Once the socket is set up, the peer program can sendto any peer it knows about, or recvfrom any peer at all (including those it does not yet know about).
So the only tricky part is bootstrapping -- getting the first packet(s) flowing so that peers can recieve them and figure out their peer addresses to talk to. One method is specifying peer addresses on the command line when you start each peer. You'll start the first one with no arguments (as it has no peers -- yet). It will just recvfrom (after socket setup) to get packets from peers. Start the second with the address of the first as an argument. It sends a packet (or several) to the first peer, which will then know about the new peer as soon as it gets the first packet. Now start a third client with the addresses of the first two on the command line...
I want to limit access to the device for more than 4 clients on IP address.
struct sockaddr_in peerAddr;
SOCK_LEN_TYPE peerAddrLen = sizeof(peerAddr);
// Yes, socket is free, try to accept a connection on it
connectionSocketArr[sockIdx] = accept(listenSocket, (struct sockaddr *) &peerAddr,
&peerAddrLen);
You can use the sockIdx variable to see how many clients are currently connected.
Instead of storing the socket returned by accept directly in the array, store it in a temporary variable. If sockIdx is larger than 3 then the new client is not allowed to connect, so send a message to the client stating that and close the socket. Otherwise store the socket in the array and increase sockIdx.