当前位置: 技术问答>linux和unix
请问如何选择网卡进行socket编程?
来源: 互联网 发布时间:2015-05-13
本文导语: 原来我有一块网卡,创建socket自然就在eth0上,由于需要,我在我的电脑上又装了一块网卡,命名为eth1,我想在eth1上也创建socket进行网络接收,但不知怎样将socket绑定在eth1上,请问各位大侠怎么设定? | ...
原来我有一块网卡,创建socket自然就在eth0上,由于需要,我在我的电脑上又装了一块网卡,命名为eth1,我想在eth1上也创建socket进行网络接收,但不知怎样将socket绑定在eth1上,请问各位大侠怎么设定?
|
SOCK_PACKET是接收链路层报文,所以不能绑定IP地址。这时应该绑定的是设备名,如下面的libpcap的代码:
/*
iface_bind_old:
Bind the socket associated with FD to the given device using the
interface of the old kernels.
*/
static int
iface_bind_old( int fd, const char *device, char *ebuf )
{
struct sockaddr saddr;
memset( &saddr, 0, sizeof(saddr) );
strncpy( saddr.sa_data, device, sizeof(saddr.sa_data) );
if( bind(fd, &saddr, sizeof(saddr)) == -1 ) {
sprintf( ebuf, "bind: %s", pcap_strerror(errno) );
return -1;
}
return 0;
}
注意是old接口。新的接口用的是新的PF_PACKET族协议:
sock_fd = socket( PF_PACKET, SOCK_RAW, htons(ETH_P_ALL) );
绑定方式为:
/*
iface_bind:
Bind the socket associated with FD to the given device.
*/
static int
iface_bind( int fd, int ifindex, char *ebuf )
{
struct sockaddr_ll sll;
memset( &sll, 0, sizeof(sll) );
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifindex;
sll.sll_protocol = htons(ETH_P_ALL);
if( bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1 ) {
sprintf( ebuf, "bind: %s", pcap_strerror(errno) );
return -1;
}
return 0;
}
参考libpcap的实现。
/*
iface_bind_old:
Bind the socket associated with FD to the given device using the
interface of the old kernels.
*/
static int
iface_bind_old( int fd, const char *device, char *ebuf )
{
struct sockaddr saddr;
memset( &saddr, 0, sizeof(saddr) );
strncpy( saddr.sa_data, device, sizeof(saddr.sa_data) );
if( bind(fd, &saddr, sizeof(saddr)) == -1 ) {
sprintf( ebuf, "bind: %s", pcap_strerror(errno) );
return -1;
}
return 0;
}
注意是old接口。新的接口用的是新的PF_PACKET族协议:
sock_fd = socket( PF_PACKET, SOCK_RAW, htons(ETH_P_ALL) );
绑定方式为:
/*
iface_bind:
Bind the socket associated with FD to the given device.
*/
static int
iface_bind( int fd, int ifindex, char *ebuf )
{
struct sockaddr_ll sll;
memset( &sll, 0, sizeof(sll) );
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifindex;
sll.sll_protocol = htons(ETH_P_ALL);
if( bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1 ) {
sprintf( ebuf, "bind: %s", pcap_strerror(errno) );
return -1;
}
return 0;
}
参考libpcap的实现。