In Raspberry Pi + C language, I sometimes want to communicate with two Ethernet interfaces, and it is a memo of what I learned at that time. Describes how to create an Ethernet socket and how to specify an Ethernet socket. We have confirmed the operation in the following environment. [Hardware] Raspberry Pi2 Model B [OS]Raspbian GNU/Linux8.0(jessie)
When using the Ethernet interface on Linux for socket communication, you can prepare for socket communication by writing the following code.
eth_com.c
deststr = IP_ADDRESS; //IP address of the connection destination#define IP_ADRESS ("192.168.0.12")
/*Generate socket*/
if((*sock = socket (PF_INET, SOCK_STREAM, 0)) < 0)
{
printf("fail to create socket\n");
return -1;
}
/*Creating an address structure for the destination server*/
memset(&server, 0, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr(deststr);
server.sin_port = htons(PORT);
/*Connection process*/
if(connect (*sock, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("fail to connect\n");
return -1;
}
However, with this code, if there are multiple Ethernet interfaces, one Ethernet interface will be used automatically. ** For example, if there are two Ethernet interfaces, "eth0" and "eth1", it will be automatically used. Will create a socket using the "eth0" interface. **
Here, if you want sockcet communication using the "eth1" interface, specify the interface with the setsockopt function </ span> .setsockopt () creates a socket Call between `` socket () ``` and the connection process
connect ()
`.
eth_com.c
deststr = IP_ADDRESS; //Set IP address
/*Generate socket*/
if((*sock = socket (PF_INET, SOCK_STREAM, 0)) < 0)
{
printf("fail to create socket\n");
return -1;
}
/** For usb-ehternet converter **/
char *opt;
opt = "eth1";
setsockopt(*sock, SOL_SOCKET, SO_BINDTODEVICE, opt, 4);
/*Creating an address structure for the destination server*/
memset(&server, 0, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr(deststr);
server.sin_port = htons(PORT);
/*Connection process*/
if(connect (*sock, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("fail to connect\n");
return -1;
}
Reference: http://stackoverflow.com/questions/3998569/how-to-bind-raw-socket-to-specific-interface
However, ** I could not communicate with the "eth1" interface even with the above code. ** If you read the web page mentioned as a reference carefully,
SO_BINDTODEVICE only works if you run as root, right? (on Linux at least) – sep332 Nov 27 '12 at 21:29
It is commented. In other words, it seems that you have to execute with root privileges. </ span> By running it with sudo, I can now communicate safely with the "eth1" interface.
Recommended Posts