Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to bind raw socket to specific interface

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)?

like image 673
Dima Avatar asked Oct 22 '10 15:10

Dima


People also ask

How do you bind a raw socket to an interface?

s_addr = inet_addr("9.1.2.3"); int rc = bind(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)); Show activity on this post. 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 .

How do you code a raw socket?

int s = socket (AF_INET, SOCK_RAW, IPPROTO_TCP); The above function call creates a raw socket of protocol TCP. This means that we have to provide the TCP header along with the data. The kernel or the network stack of Linux shall provide the IP header.

How do you bind a socket address in a socket?

Bind the socket to an address using the bind() function; Listen for connections with the listen() function; Accept a connection with the accept() function system call. This call typically blocks until a client connects with the server.

What is the use bind () socket call?

The bind() function binds a unique local name to the socket with descriptor socket. After calling socket(), a descriptor does not have a name associated with it. However, it does belong to a particular address family as specified when socket() is called. The exact format of a name depends on the address family.


1 Answers

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

like image 75
Andrew Sledge Avatar answered Sep 18 '22 16:09

Andrew Sledge