Linux 套接字编程 套接字选项SO_BINDTODEVICE 绑定接口 示例
生活随笔
收集整理的這篇文章主要介紹了
Linux 套接字编程 套接字选项SO_BINDTODEVICE 绑定接口 示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
man socket(7)里對該選項的描述:
SO_BINDTODEVICEBind this socket to a particular device like “eth0”, as speci‐fied in the passed interface name. If the name is an emptystring or the option length is zero, the socket device bindingis removed. The passed option is a variable-length null-ter‐minated interface name string with the maximum size of IFNAM‐SIZ. If a socket is bound to an interface, only packetsreceived from that particular interface are processed by thesocket. Note that this works only for some socket types, par‐ticularly AF_INET sockets. It is not supported for packetsockets (use normal bind(2) there).Before Linux 3.8, this socket option could be set, but couldnot retrieved with getsockopt(2). Since Linux 3.8, it isreadable. The optlen argument should contain the buffer sizeavailable to receive the device name and is recommended to beIFNAMSIZ bytes. The real device name length is reported backin the optlen argument.將套接字綁定到指定接口,例如eth0等。如果綁定了接口,這個套接字只能處理由該接口收到的數據。 注意,并不是所有套接字類型都有這個選項。AF_INET套接字支持,但是packet 套接字不支持(不過,可以使用bind函數綁定地址)如果有多個接口,例如eth0, eth1, ethx......,就可以在創建套接字的時候綁定相應的接口發送數據,例如我的電腦里有兩個接口 :
在創建套接字的時候就可以綁定相應的接口發送數據,demo:
/** Desrciption : 套接字選項SO_BINDTODEVICE使用,需要root權限執行* Author : mason* Date : 201809*/#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <net/if.h> #include <errno.h>int main() {int sock;struct sockaddr_in addr, raddr;char buffer[] = "hello world";/* 指定接口 */struct ifreq nif;char *inface = "eth0";strcpy(nif.ifr_name, inface);/* 創建套接字 */sock = socket(AF_INET, SOCK_DGRAM, 0);if (-1 == sock){printf("create socket fail \r\n");return;}else{printf("create socket success \r\n");}if (inet_aton("192.168.80.129", &addr.sin_addr) != 1){printf("addr convert fail \r\n");close(sock);return;}addr.sin_family = AF_INET;addr.sin_port = htons(8000);if (inet_aton("192.168.80.1", &raddr.sin_addr) != 1){printf("addr convert fail \r\n");close(sock);return;}raddr.sin_family = AF_INET;raddr.sin_port = htons(8000);#if 0 //綁定地址if (bind(sock, (struct sockadd *)&addr, sizeof(addr)) != 0){printf("bind fail \r\n");close(sock);return ;}else{printf("bind success \r\n");}#endif/* 綁定接口 */if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, (char *)&nif, sizeof(nif)) < 0){close(sock);printf("bind interface fail, errno: %d \r\n", errno);return ; }else{printf("bind interface success \r\n");}/* 發送 */sendto(sock, buffer, sizeof(buffer), 0, ((struct sockadd *)&raddr),sizeof(raddr));close(sock);return; }分別綁定eth0, eth1發送數據,抓包如下圖,可以看到有不同的源地址發送。
程序執行的時候需要使用sudo權限,不然會提示綁定接口失敗。
感覺類似的功能完全可以由bind接口實現,即綁定指定IP地址。
?
總結
以上是生活随笔為你收集整理的Linux 套接字编程 套接字选项SO_BINDTODEVICE 绑定接口 示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 股票蜡烛图怎么看
- 下一篇: Linux 模拟网络丢包和延迟命令