I am an experienced Linux socket programmer and am writing a server application which has many outgoing interfaces. Now server socket binds to a random source port in the start of the process along with INADDR_ANY.
Later at some point when submitting response to a specific node, i need to assign a fixed source ip address. The standard way to do this is calling bind. However, bind is called once for the port number, successive calls fail with invalid argument error.
Creating a new socket is not really a good choice since i will have to be doing this very often upon responding to some clients.
I have also explored SO and a lot of socket options such as IP_FREEBIND, but it doesn't quite suite my scenario.
Perhaps using IP_PKT_INFO and setting source address might work unless it suffers the same problem i.e. not allowing a socket once bound to INADDRANY to rebind to a fixed source ip latter.
Is there a way to unbind an existing socket or an alternate way to setting source ip address in outgoing packet?
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0)
printf("Failed creating socket\n");
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(1500);
addr.sin_addr.s_addr = INADDR_ANY;
// first bind succeeds
if ( (status = bind(sock, (struct sockaddr *) &addr, sizeof(addr))) < 0)
printf("bind error with port %s\n", strerror(errno));
struct sockaddr_in src_addr;
memset(&src_addr, 0, sizeof(struct sockaddr_in));
src_addr.sin_family = AF_INET;
if (inet_aton("10.0.2.17", &(src_addr.sin_addr)) == 0)
printf("Failed copying address\n");
// second bind fails
if((status = bind(sock, (struct sockaddr *)&src_addr, sizeof(src_addr))) < 0)
printf("re bind error with ip %s\n", strerror(errno));
Any ideas in this regard will be highly appreciated. I have gone through considerable material on sockets, SO etc. but no success yet.
I finally found the solution myself so accepting my own answer (shameless but correct plugin), supplemented with code sample.
I originally wanted to rewrite source address of an outgoing packet without creating the socket again where the socket was already bound. Calling bind multiple times fail for this case, and (in my particular situation), i was not able to just have separate sockets for each source ip and use it.
I found some references in IP_PACKET_INFO but it was a pain to get it to work correctly. Following reference was helpful.
Setting source of udp socket
Sample Code
Here is a trivial application which creates a udp socket, binds it to a local port, then before sending a particular message, it appends the outgoing source ip address. Keeping in mind that in my case, i created a sudo interface and assigned it another ip. The send call will fail if this is not the case.
int status=-1;
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0)
printf("Failed creating socket\n");
int opt = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in bind_addr;
memset(&bind_addr, 0, sizeof(struct sockaddr_in));
bind_addr.sin_family = AF_INET;
bind_addr.sin_port = htons(44000); // locally bound port
if((status = bind(sock, (struct sockaddr *)&bind_addr, sizeof(bind_addr))) < 0)
printf("bind error with port %s\n", strerror(errno));
// currently using addr as destination
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(80); // destination port
if (inet_aton("74.125.236.35", &(addr.sin_addr)) == 0)
printf("Failed copying remote address\n");
else
printf("Success copying remote address\n");
struct sockaddr_in src_addr;
memset(&src_addr, 0, sizeof(struct sockaddr_in));
src_addr.sin_family = AF_INET;
if (inet_aton("10.0.2.17", &(src_addr.sin_addr)) == 0)
printf("Failed copying src address\n");
else
printf("Success copying src address\n");
char cmbuf[CMSG_SPACE(sizeof(struct in_pktinfo))];
char msg[10] = "hello";
int len = strlen(msg);
struct msghdr mh;
memset(&mh, 0, sizeof(mh));
struct cmsghdr *cmsg;
struct in_pktinfo *pktinfo;
struct iovec iov[1];
iov[0].iov_base = msg;
iov[0].iov_len = len;
mh.msg_name = &addr; // destination address of packet
mh.msg_namelen = sizeof(addr);
mh.msg_control = cmbuf;
mh.msg_controllen = sizeof(cmbuf);
mh.msg_flags = 0;
mh.msg_iov = iov;
mh.msg_iovlen = 1;
// after initializing msghdr & control data to
// CMSG_SPACE(sizeof(struct in_pktinfo))
cmsg = CMSG_FIRSTHDR(&mh);
cmsg->cmsg_level = IPPROTO_IP;
cmsg->cmsg_type = IP_PKTINFO;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
pktinfo = (struct in_pktinfo*) CMSG_DATA(cmsg);
//src_interface_index 0 allows choosing interface of the source ip specified
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst = src_addr.sin_addr;
int rc = sendmsg(sock, &mh, 0);
printf("Result %d\n", rc);
The key statement is
pktinfo->ipi_spec_dst = src_addr.sin_addr;
where we are specifying the source ip address to be used. The rest of things like cmsg struct etc. are merely used in order to be able to write ipoktinfo struct ourselves
There is no way to unbind and rebind an existing socket.
Why don't you create a socket for each interface instead? Since the UDP/IP protocol is connectionless, you can choose the source IP address by choosing which socket you use to send the reply with; there is no need to use the same socket the incoming datagram was received on.
The downsides are that you can no longer bind to the wildcard address, and you must use select(), poll(), multiple threads, or some other mechanism to receive datagrams from multiple sources concurrently. You'll also need some logic to efficiently pick the socket based on the client IP address.
In most cases, I suspect that adding a few route entries to route each remote IP address to the desired host IP address, and using a separate socket for each host IP address and port combination, solves the issues perfectly -- and using the very efficient kernel functionality to do so. While the behaviour may be an application requirement, I suspect it is better solved using the network interface configuration instead. Unfortunately, often the requirements are written by semi-functional idiots better suited for manual labor, and your hands are tied.. if so, I commiserate.
If you have a test network with workstations having multiple physical network interfaces, I can provide a simple example C99 test program you can use to verify the design works.
Related
I have an assignment to make a Routing Information Protocol sniffer and a program in C/C++ capable of sending custom RIP entry using the information gathered from the sniffer.
I'm running both in a school provided Ubuntu Virtualbox image, which is connected via "Internal Network" option to a BSD image running a routing daemon generating RIP traffic.
I got to the part where I need to send the custom packet to the "router" but I hit a wall when trying to send it from port 520.
From the RFC 1058 describing the RIP protocol I gathered that in order for a router to acknowledge a new route, the RIP message has to come from and to the port 520.
I can send my packet to port 520 of the router just fine, but the source port is always a random port assigned by system after my binding fails with an errno message "Cannot assign requested address".
The packet itself looks just fine in WireShark, with the exception of the source port which is for example 60818.
I am doing the following in my response program:
#define ROUTERADDR "10.0.0.1"
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in router;
router.sin_family = AF_INET;
router.sin_port = htons(520);
router.sin_addr.s_addr = inet_addr(ROUTERADDR);
bind (fd, (struct sockaddr*)&router, sizeof(router));
connect (fd, (struct sockaddr*)&router, sizeof(router));
send(fd, &payload, sizeof(payload), 0);
close(fd);
Binding to a port < 1024 requires root permission, unless you add your executable to CAP_NET_BIND_SERVICE capability as below.
setcap 'cap_net_bind_service=+ep' /path/to/executable
There is another issue in your code, where you are trying to bind to router's address. You need to bind to the specific local address or INADDR_ANY, as shown below.
struct sockaddr_in local, router;
local.sin_family = AF_INET;
local.sin_port = htons(520);
local.sin_addr.s_addr = htonl(INADDR_ANY);
bind (fd, (struct sockaddr*)&local, sizeof(local));
router.sin_family = AF_INET;
router.sin_port = htons(520);
router.sin_addr.s_addr = inet_addr(ROUTERADDR);
connect (fd, (struct sockaddr*)&router, sizeof(router));
You should check the return value of your system calls, so you know when things don't work, as in your case the bind() call likely fails.
In your case bind() would fail because you try to bind to a port on the remote address you're sending to, which you cannot do.
bind() specifies the local endpoint you want to use, thus you should specify one of the local IP addresses you want to send from.
Or you can bind the socket to any local address, using INADDR_ANY. so you might want to create another struct sockaddr_in and do it like this:
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(520);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(fd, (struct sockaddr*)&my_addr, sizeof(my_addr)) != 0) {
perror("bind() failed");
}
Rewritten to try and be clear on what I need.
My goal is to duplicate the function of a device made by Digital Yacht in an embedded Intel Edison processor running C and Linux. The device sends via UDP to phone apps such as iRegatta and others. To set up the app, only the port number is entered. No ip address is entered in UDP mode on the app. I thought this was trivial but the experts here so far have said it is impossible so it must not be trivial. Perhaps that is why with all my hours of reading I cannot find an example. I am being voted down because, I am told, that what I am trying to do it impossible but it is not as it is done. I don't know how it is done, which is why I came to experts here.
I want to send nmea messages that might look like this:
$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
and I want any number of random Android phones to be able to receive them with the appropriate app. There are many apps that can be set up to receive UDP data where you just specify a port number. There is no ip address involved in the setup of the apps. Also, I do not wish to receive anything from the Android phones. This is one way and no ability to re-transmit so if a message does not get there, it has another chance next time. Everything is updated once a second.
I tried the following and I do not get data in the app. From the comments, I must need to add some kind of router function in my Linux machine.
void init_udp(){
return;
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock < 0){
printf("ER UDP Socket error\n");
}
else printf("UP Socket %d OK\n",sock);
}
void write_udp(char *buf){
return;
// nmea data is in buff
if (sock >= 0){
int on = 1;
setsockopt( sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on) );
struct sockaddr_in address = {0};
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr( "255.255.255.255" ); //
address.sin_port = htons( 3000 );
if ( sendto( sock, buf, strlen(buf), 0, (struct sockaddr*)&address, sizeof(address) ) < 0) printf("ER UDP send error\n");
else {
printf("UP %s\n",buf);
}
}
}
I am not really sure what I need to do.
What you want to do is send a UDP packet to a broadcast IP address. This will send to thing in the subnet.
eg 10.255.255.255 is the broadcast address for the 10.x.x.x subnet. You can also use the global 255.255.255.255 which should also send to your subnet and no router is going to pass that on to another one these days.
Also you need to make your socket able to send broadcast messages. In particular you need the option SO_BROADCAST set. The following is specifically Windows because of the BOOL. Its presumably an int for most platforms.
BOOL on = TRUE;
setsockopt( sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on) );
Also you can't use send() for a UDP socket unless its "connected", so you should use sendto() and use the broadcast address.
To specify an address and port, use need to create a socket address.
struct sockaddr_in address = {0};
address.sin_family = AF_INET;
address.sin_add.s_addr = inet_addr( "255.255.255.255" );
address.sin_port = htons( 3000 );
sendto( sock, buff, strlen(buff), 0, (struct sockaddr*)&address, sizeof(address) );
Note the use of the typecast. This is because sendto takes a sockaddr which is a generic address type, and here we are using an IPV4 address specifically. The sockaddr_in maps onto the sockaddr
Here's the deal, I'm writing a simple tcp socket server in C (with unix system calls) that I'm not able to get to accept connections.
From what I can tell, I get through the server initialization just fine, but when I try to connect to the port that I print out (see code below) it refuses as if nothing is there.
More to the point, when I netstat that port isn't even in use. I'm not throwing any errors with my current set up, I'm all dried up for ideas.
int main(){
int sock_fd;
int conn_fd;
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
socklen_t* serlen;
socklen_t* clilen;
clilen = malloc(sizeof(socklen_t));
serlen = malloc(sizeof(socklen_t));
*serlen = sizeof(serv_addr);
*clilen = sizeof(cli_addr);
/*=============================Create Socket=============================*/
//Create Socket
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if(sock_fd<0){
fprintf(stderr,"error creating socket\n");
exit(1);}
//Initialize Server Address Struct
bzero((char *) &serv_addr, *serlen);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = 0;
/*=============================Bind Address==============================*/
//Bind socket to an address
if(bind(sock_fd,(struct sockaddr*)&serv_addr,*serlen)<0){
fprintf(stderr,"error binding\n");
exit(1);}
//Get socket data
if(getsockname(sock_fd,(struct sockaddr*)&serv_addr, serlen)<0){
fprintf(stderr,"error with socket name");
exit(1);}
/*=============================Server Started============================*/
//Listen for connections
listen(sock_fd,32);
//Print port
printf("%i", serv_addr.sin_port);
conn_fd = accept(sock_fd,(struct sockaddr*)&cli_addr,clilen);
/**Do something exciting with my new connection**/
}
Are you really trying to listen on port zero? Try a high port number, preferably > 1024. /etc/services will give a hint about free ports - but it only a set of comments, those port numbers are not enforced.
Edit: another hint. The port number should be in network order, so the assignment should use htons(). It could be that the "random numbers" you are getting are simple numbers that appear garbled because you might be on a little-endian machine (like Intel). When you print them, convert them back using ntohs().
props to #askmish for inspiring this one
//Print port
printf("%i", serv_addr.sin_port);
becomes
//Print port
printf("%i", htons(serv_addr.sin_port));
In your code:
Instead of:
serv_addr.sin_port = 0;
try this:
serv_addr.sin_port=htons(2056);//Any port no.
Instead of:
listen(sock_fd,32);
try this:
if(listen(sock_fd,SOMAXCONN)<0)//Just to be sure that you are considering max. no. of requests
{ fprintf(stderr,"error with listen");
exit(1);}
Also for:
conn_fd = accept(sock_fd,(struct sockaddr*)&cli_addr,clilen);
Add this:
if(conn_fd <0)
{
//handle the error here
}
If none of these solve your issues, then, there might be problem with the client code or your server environment.
I'm trying to implement a basic UDP protocol wherein a Sender sends a UDP datagram to a Service, which then sends a response datagram back, using the source address and source port from the incoming datagram.
Normally you'd have the Sender also listen for the response on that port. But I want the response to be picked up by a separate program (the Listener) also running on that host. So:
On host A, Listener starts and binds to port 12345, and blocks on recvfrom.
On host A, Sender sends datagram to Service running on host B, setting the source address and port to host A, port 12345.
Service on host B sends a response to host A port 12345.
Response is picked up by Listener.
Setting the source address and port is done by binding to them. So I need both Sender and Listener to bind to the same port. Setting SO_REUSEADDR in both allows this. Note that I'm not using multicast here.
But the responses aren't reliably being picked up by Listener. There are two exceptions I've observed:
I find that if the Sender closes the socket immediately after sending the first datagram, then the response will get to the Listener.
Alternatively, if the Sender is started first and binds before the Listener, the responses will get picked up by the Listener.
I've been working from examples from the internet and haven't found documentation that clearly describes what should happen. But a few places I've seen have hinted that, for Unicast, only the most recent process to bind to the port will receive datagrams sent to it.
My question is, can I send UDP datagrams so that responses (sent using the source address and port) will be picked up by another process? If the above process can't be made to work, is there a way to set the source information on an outgoing datagram without binding to that port?
A few other points:
Each process should be started independently and be able to be restarted without interfering with the other. So I don't think I can have one open the socket and spawn the other.
I don't need to receive packets from both processes. One process only sends, and the other only receives.
Ideally, the solution would be portable enough to run on common Unixes and Windows.
Finally, if it's simply not possible then I'll fall back to using a single process to perform both functions. I'm not too stressed about it but I am interested in doing it if it is possible somehow. :-)
Networking code follows...
Sender code
void run(Options *options)
{
struct sockaddr_in si_me, si_other;
int s;
socklen_t slen = sizeof(si_other);
int reuse = 1;
struct hostent *he;
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
die("socket");
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) != 0)
die("setsockopt");
// Bind to the "listen port", so that outgoing datagrams have the correct source information
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(options->listen_port);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (struct sockaddr *) &si_me, sizeof(si_me)) != 0)
die("bind");
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(options->service_port);
if (!(he = gethostbyname2(options->service_host, AF_INET)))
die("gethostbyname2");
memmove(&si_other.sin_addr.s_addr, he->h_addr, he->h_length);
while (1)
{
int len;
char *buf;
// Create outgoing message in buf
...
if (sendto(s, buf, len, 0, (struct sockaddr *) &si_other, slen) == -1)
die("sendto");
}
close(s);
}
Listener code
static void run(Options *options)
{
struct sockaddr_in si_me, si_other;
int s;
socklen_t slen = sizeof(si_other);
char buf[BUFLEN];
int reuse = 1;
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
die("socket");
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) != 0)
die("setsockopt");
// Bind to the same "listen port" to pick up responses to datagrams sent by Sender
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(options->listen_port);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (struct sockaddr *) &si_me, sizeof(si_me)) == -1)
die("bind");
while (1)
{
int nr;
nr = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen);
if (nr == -1)
die("recvfrom");
// Process the received message
...
}
close(s);
}
A related question is Using netcat to send a UDP packet without binding, where one answer seems to suggest it should be possible using SO_SOCKADDR, but did not quite explain how it would work in my case.
is there a way to set the source information on an outgoing datagram
without binding to that port?
There is no portable way. A solution for Linux, using IP_PKTINFO, is this answer to How to re bind a udp socket in Linux.
1: You can send from different port on B
A binds 12345 sends to B:12345
B:12345 - process 1 - recv
B:12346 - process 2 - send to A:12345
2: You can construct packet with fake back address with raw sockets
First solution is better
I'm trying to simulate a DHCP server as a university task. It's required to execute at least 2 servers (or more up to 255) since several clients will be sending messages to these servers using BROADCAST (that's where the limit of 'only' 255 servers comes from).
But when I'm trying to execute 2 servers in 2 different terminals in Ubuntu, the second server executed is rejected. I guess it's due to IP at the same localhost or whatever (I'm sorry but I don't know too much about communication protocols)
How can I run several servers on the same machine? Our teacher told us about using VMWare to run another Linux OS, and try to run both, but for me this solution is far away from my thoughts... I will post the server and client connection statements, although I don't know if there's a problem with the C statements, or the OS configuration, etc.
Server:
int sockfd, newsockfd, clilen, n;
struct sockaddr_in cli_addr, serv_addr ;
char host_name[200];
int size = sizeof(struct DHCP);
char buffer[size];
struct MACIP *macip;
if ((sockfd = socket(AF_INET, SOCK_DGRAM,0)) < 0) {
printf("server: can't open datagram socket\n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(0);
serv_addr.sin_port = htons(SERV_UDP_PORT);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <0) {
printf("server: can't bind local address\n");
return -1;
}
Client:
int sockfd, n, clilen;
struct sockaddr_in serv_addr, cli_addr;
char serv_host_addr[30];
int size = sizeof(struct DHCP);
char buffer[size];
printf("Dirección IP del servidor (a.b.c.d) => ");
gets(serv_host_addr);
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("client: can't open datagram socket");
return -1;
}
int opt=1;
if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST,&opt, sizeof(opt))<0) {
perror("Error opcion socket");
close(sockfd);
return 1;
}
bzero((char *)&cli_addr,sizeof(cli_addr));
cli_addr.sin_family = AF_INET;
if (bind(sockfd, (struct sockaddr *) &cli_addr,sizeof(cli_addr)) < 0) {
perror("client: can't bind a port");
return -1;
}
serv_addr.sin_family = AF_INET;
inet_pton(AF_INET, serv_host_addr,&serv_addr.sin_addr);
//serv_addr.sin_addr.s_addr = inet_addr(serv_host_addr);
serv_addr.sin_port = htons(SERV_UDP_PORT);
Thank you very much in advance.
Every instance of your UDP server must listen on another port. Key line in your code is this:
serv_addr.sin_port = htons(SERV_UDP_PORT);
Looks like you have the port number as a constant (SERV_UDP_PORT). To make multiple servers run at the same time you need another port for each one.
Probably best solution in your case is to have a command line argument that would define the port on which you start your server.
Each client needs to know which port (and address of course) to connect to as well. So make your client to accept similar command line argument.
To run multiple servers, they should listen on different ports on same network interface. You may get away by using two network interfaces (say wifi and ethernet) on same network with different ips.
You might try to set up alias interfaces on an existing interface. Such alias interfaces then get their own ip address each.
Using the loopback interface (lo), which typical has 127.0.0.1 assigned, such aliases to this interface could then be called lo:0, lo:1 ... and would carry the ip addresses 127.0.0.2, 127.0.0.3, ....
For details on how to achieve this see man ifconfig.