My application is running on CentOS 5.5.
I'm using raw socket to send data:
sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (sd < 0) {
// Error
}
const int opt_on = 1;
rc = setsockopt(m_SocketDescriptor, IPPROTO_IP, IP_HDRINCL, &opt_on, sizeof(opt_on));
if (rc < 0) {
close(sd);
// Error
}
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = my_ip_address;
if (sendto(m_SocketDescriptor, DataBuffer, (size_t)TotalSize, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0) {
close(sd);
// Error
}
How can I bind this socket to specific network interface (say eth1)?
const char *opt;
opt = "eth0";
const len = strnlen(opt, IFNAMSIZ);
if (len == IFNAMSIZ) {
fprintf(stderr, "Too long iface name");
return 1;
}
setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, opt, len);
First line: set up your variable
Second line: tell the program which interface to bind to
Lines 3-5: get length of interface name and check if it's size not too big.
Six line: set the socket options for socket sd, binding to the device opt.
setsockopt prototype:
int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen);
Also, make sure you include the if.h, socket.h and string.h header files
As mentioned earlier, the correct thing to do is use the struct ifreq to specify the interface name. Here is my code sample.
#define SERVERPORT 5555
...
struct ifreq ifr;
/* Create the socket */
sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd < 0)
{
printf("Error in socket() creation - %s", strerror(errno));
}
/* Bind to eth1 interface only - this is a private VLAN */
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth1");
if ((rc = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) < 0)
{
perror("Server-setsockopt() error for SO_BINDTODEVICE");
printf("%s\n", strerror(errno));
close(sd);
exit(-1);
}
/* bind to an address */
memset(&serveraddr, 0x00, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(SERVERPORT);
serveraddr.sin_addr.s_addr = inet_addr("9.1.2.3");
int rc = bind(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
I would also like to add that from a security perspective, while it is good to bind the socket to an interface, it does not make sense to use INADDR_ANY as the listening IP address. Doing so would make the port appear open in netstat on all network interfaces.
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name
tcp 0 0 0.0.0.0:5555 0.0.0.0:* LISTEN 0 210898 26996/myserver
Instead, I specified an IP address specific to the interface being used (a private VLAN). This fixed the netstat output too:
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name
tcp 0 0 9.1.2.3:5555 0.0.0.0:* LISTEN 0 210898 26996/myserver
Bind socket to specific interface IP address
int bind_using_iface_ip(int fd, char *ipaddr, uint16_t port)
{
struct sockaddr_in localaddr = {0};
localaddr.sin_family = AF_INET;
localaddr.sin_port = htons(port);
localaddr.sin_addr.s_addr = inet_addr(ipaddr);
return bind(fd, (struct sockaddr*) &localaddr, sizeof(struct sockaddr_in));
}
Bind socket to specific interface name
int bind_using_iface_name(int fd, char *iface_name)
{
return setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface_name, strlen(iface_name))
}
In bind_using_iface_ip, to bind to any port 0 should be passed. And also if the fd is raw socket then need to pass port as 0. This bind mechanism is common for all kind of sockets like raw, dgram and stream.
Related
we have a requirement for UDP multicasting in our project using Linux 4.1 kernel
with static ip address.
basic UDP multicasting using sendto function to send data is working fine with device static ip 10.13.204.100, issue comes when i change ip of the device to 10.13.204.101 or any other ip in the same series, the udp multicasting is showing an error
sendto: network unreachable
im initializing the UDP as shown below
int udp_init()
{
char multicastTTL = 10;
// Create UDP socket:
memset(&socket_desc, 0, sizeof(socket_desc));
socket_desc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (socket_desc < 0)
{
perror("socket");
return 1;
}
udp_socket_fd = socket_desc;
printf("udp_socket_fd=>%d\nsocket_desc==>%d\n", udp_socket_fd, socket_desc);
/* Set the TTL (time to live/hop count) for the send */
// if (setsockopt(socket_desc, IPPROTO_IP, IP_MULTICAST_TTL, &multicastTTL, sizeof(multicastTTL)) < 0)
if (setsockopt(socket_desc, SOL_SOCKET, SO_REUSEADDR, &multicastTTL, sizeof(multicastTTL)) < 0)
{
perror("setsockopt");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr)); /* Zero out structure */
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(EXAMPLE_GROUP); // INADDR_ANY;
server_addr.sin_port = htons(EXAMPLE_PORT); // htons(udp_port);
// bind to receive address
//
if (bind(socket_desc, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
perror("bind");
printf("line %s-->%s:%d\n", __FILE__, __FUNCTION__, __LINE__);
return 1;
}
}
once the ip is changed im closing the UDP socket using
close(socket_desc)
once again im using the udp_init function to initialize the UDP then im sending using sendto function to transmit the data but im get sendto:network unreachable
thanks in advance
"sendto: network unreachable" means you do not have a route to the new address, add it or change the mask for the .100 route
There is my function. I pass argument port as 80 and I always can not bind socket.
int create_socket(int port)
{
int sock;
struct sockaddr_in name;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
fprintf(stderr, "Can not create socket\n");
return -1;
}
//Assigning a name to the socket
name.sin_family = AF_INET;
name.sin_port = htons((unsigned short)port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (const struct sockaddr *) &name, sizeof(name)) == -1) {
fprintf(stderr, "Can not bind socket\n");
return -1;
}
return sock;
}
Typically port number less than 1024 are used by well known network servers and in linux, root privilege is required to open these ports.
80 is HTTP port and so your program requires root privilege.
I am trying to listen to multicast on all interfaces in system, but responds only on this on which I've received multicast packet.
What I've did is to create a socket for each of the interfaces and here the problems starts.
When I bind interface to INADDR_ANY it will receive packets for all interfaces and send on default one. If I bind port to specific interface it will not receive multicast packet (but it will be able to send it on correct interface).
I've tried setting options like IP_ADD_MEMBERSHIP or IP_MULTICAST_IF but without success.
I think the other options whould be to create one socket to receive on all ifs and senders sockets for all interfaces, but on this approach I have no idea on which ifs packet entered...
Code samples (simplified, without error handling and stuff):
Creating socket:
//here i am looping over all interfaces from getifaddrs
struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;
sockets[i] = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
setsockopt(sockets[i], SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
mreq.imr_multiaddr.s_addr=inet_addr(MDNS_ADDRESS);
mreq.imr_interface.s_addr=pAddr->sin_addr.s_addr;
setsockopt(sockets[i], IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
setsockopt(sockets[i], IPPROTO_IP, IP_MULTICAST_IF, &pAddr, sizeof(struct in_addr));
memset(&my_addr, 0, sizeof(struct sockaddr_in));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = INADDR_ANY; //or pAddr->sin_addr.s_addr;
my_addr.sin_port = htons(port);
bind(sockets[i], (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1);
Receiving and sending:
recvfrom(sockfd, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&their_addr, &addr_len);
//do some magic and response (response should be a multicast too)
destination.sin_addr.s_addr = inet_addr(MULTICAST_ADDRESS);
destination.sin_family = AF_INET;
destination.sin_port = htons( port );
sendto(sockfd, buffer, len, 0, (struct sockaddr *)&destination, sizeof destination);
I would like to create something similar in work to mDNS so when packet entered on specific interface program should answer on the same if with some data about this if. It should not send this on other ifs as it may not be relevant for them, but it should send it as multicast so any other host in same network will receive the respond.
You should only need one socket for this.
First bind to INADDR_ANY and your port of choice. Then call setsockopt with IP_ADD_MEMBERSHIP on each interface you want to receive multicast on. Finally, call setsockopt with IP_MULTICAST_IF on the interface you want to send multicast on. Make sure to check for errors on each call.
int socket s;
struct sockaddr_in sin;
struct ip_mreq mreq;
struct in_addr out_addr;
bzero(&sin,sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr=htonl(INADDR_ANY);
sin.sin_port = htons(1044); // or whatever port you listen on
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket failed");
exit(1);
}
if (bind(s, (struct sockaddr *)&sin, sizeof(sin))==-1) {
perror("bind failed");
exit(1);
}
// Do this in a loop for each interface
mreq.imr_multiaddr = inet_addr("230.4.4.1"); // your multicast address
mreq.imr_interface = inet_addr("192.168.1.1"); // your incoming interface IP
if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) == -1) {
perror("Error joining multicast group");
exit(1);
}
out_addr.s_addr = inet_addr("192.168.1.1"); // your outgoing interface IP
if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, (char *)&out_addr,sizeof(out_addr))== -1) {
perror("Error setting outgoing interface");
exit(1);
}
When using multicast, you should always bind to the INADDR_ANY address. Failure to do so breaks multicast on Linux systems.
Initially, I accepted #dbush answer as it allowed me to get on right track. For sake of completeness I post more detailed answer and as suggested by him I accepted my own answer.
Some of the code was found here: Setting the source IP for a UDP socket
I was able to do all of this with single socket and setting IP_PKTINFO.
Code samples (simplified, without error handling and stuff):
Creating socket:
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) == -1) {
perror("socket");
exit(1);
}
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) < 0) {
perror("setsockopt");
exit(1);
}
optval2 = 1;
if(setsockopt(sockfd, IPPROTO_IP, IP_PKTINFO, &optval2, sizeof(optval2)) < 0) {
perror("setsockopt");
exit(1);
}
memset(&my_addr, 0, sizeof(struct sockaddr_in));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = INADDR_ANY;
my_addr.sin_port = htons(5353);
if (bind(sockfd, (struct sockaddr *)&my_addr,
sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
Receiving and responding:
char buf[MAXBUFLEN];
char cmsgbuf[MAXBUFLEN];
struct iovec iov[1];
iov[0].iov_base=buf;
iov[0].iov_len=sizeof(buf);
struct cmsghdr *cmsg;
struct msghdr message;
message.msg_name=&their_addr;
message.msg_namelen=sizeof(their_addr);
message.msg_iov=iov;
message.msg_iovlen=1;
message.msg_control=cmsgbuf;
message.msg_controllen=MAXBUFLEN;
if ((numbytes = recvmsg(sockfd, &message, 0)) == -1) {
perror("recvfrom");
exit(1);
}
for (cmsg = CMSG_FIRSTHDR(&message); cmsg != NULL; cmsg = CMSG_NXTHDR(&message, cmsg)) {
// ignore the control headers that don't match what we want
if (cmsg->cmsg_level != IPPROTO_IP ||
cmsg->cmsg_type != IP_PKTINFO)
{
continue;
}
struct in_pktinfo *pi = CMSG_DATA(cmsg);
addr = pi->ipi_spec_dst.s_addr;
}
//DO SOME MAGIC
//HERE WE ARE SETTING ADDR - INTERFACE WITH THIS ADDR WILL SEND MULTICAST
sock_opt_addr.s_addr = addr;
setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_IF, &sock_opt_addr, sizeof(sock_opt_addr));
sendto(sockfd, buffer, len, 0, (struct sockaddr *)&destination, sizeof destination);
I'm writing a simple UDP client and an error returned as "invalid argument", but I don't know what's wrong. It is compiled on linux. My code is as below.
int udp_fd = -1;
struct sockaddr_in addr;
int port = 1701;
udp_fd = socket(AF_PPPOX, SOCK_DGRAM, 0);
if (udp_fd < 0) {
printf("fail to get UDP socket\n");
return 0;
}
memset((char *) &addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("31.25.210.118");
addr.sin_port = htons(port);
if(connect(udp_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
printf("UDP connect failed, errno = %s\n", strerror(errno));
return 0;
}
You are using an AF_INET address with an AF_PPPoX socket. This is mixing apples and parakeets.
PPP stands for "point-to-point", there is no such thing as IP address in this domain. Pick your game. You either connect over the Internet, and use socket(AF_INET, ..., or connect over PPP and use one of the PPP protocols like PX_PROTO_OLAC or PX_PROTO_OPNS, and a corresponding socket address type (sockaddr_pppolac or sockaddr_pppopns) instead of sockaddr_in.
I have setup a UDP receiver, as:
int rx_socket;
struct sockaddr_in my_addr;
struct sockaddr_in rem_addr;
socklen_t addrlen = sizeof(rem_addr);
rx_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(9900);
rc = bind(rx_socket, (struct sockaddr *) &(my_addr), sizeof(my_addr));
if (!rc) {
printf("BIND SUCCESSFULL\n");
}
char buf[250];
while(1) {
printf("WAITING\n");
recvfrom(rx_socket, buf, sizeof(buf), 0, (struct sockaddr *)&rem_addr, &addrlen);
printf("RECEIVED\n");
}
The recvfrom() never returns. I have done some Wireshark analysis, and it indicates the packets are there:
Summary:
User Datagram Protocol, Src Port: 57506 (57506), Dst Port: iua (9900)
Checksum: 0x14a2 [validation disabled]
Data (8 bytes)
Any help will be appreciated.
EDIT:
An interesting observation is that the source, which is a DSP fails to send packets, i.e., sendto() returns -1, until I ping to it, from destination. Right after the ping, the source can start transmitting packets.
EDIT 2:
Here is the sender's code:
int fd;
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(9900);
inet_aton("10.0.201.102", &(my_addr.sin_addr));
char buf[250];
for (;;) {
int bytesSent = sendto(fd, buf, 8, 0,
(struct sockaddr *) &(my_addr), sizeof(my_addr));
printf("sent: %d bytes\n", bytesSent);
sleep(1000);
}
So the problem turned out to be with virtualbox. My sender is on host, but receiver is on a virtual machine. If I run the receiver on the host as well, UDP packets are being received.