简体   繁体   中英

bind raw socket to specific address

I am doing raw socket programming in C. I am creating my own ethernet, ip and tcp headers. Then I add data to the packet and send it. Then I need to wait for response from the other program.

I have one computer. So using lo as my interface. I have something like

CreateSocket
BindSocketToInterface
Sendto
recvfrom

Now it is receiving it's own data which is undesirable. So I am thinking to bind socket to specific address. Can I do it? Also How to do it??

Can select solve this problem ??

Thanks :)

Like if you want interface then as follows

char *opt;
opt = "eth0";
setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, opt, 4);

But if you want port address then

You cannot bind a raw socket to a specific port because "port" is a concept in TCP and UDP, not IP. Look at the header diagrams for those three protocols and it should become obvious: you are working at a lower level, where the concept of port is not known.

you can use setsockopt to bind it to a specific device.

struct ifreq *ifr = <populate some values>;
setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)ifr, sizeof(struct ifreq))

Try the above code and it should work. populate the ifreq correctly for the required network device.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM