简体   繁体   中英

Raw socket sendto() failure in OS X

When I open a raw socket is OS X, construct my own udp packet (headers and data), and call sendto(), I get the error "Invalid Argument". Here is a sample program "rawudp.c" from the web site http://www.tenouk.com/Module43a.html that demonstrates this problem. The program (after adding string and stdlib #includes) runs under Fedora 10 but fails with "Invalid Argument" under OS X. Can anyone suggest why this fails in OS X? I have looked and looked and looked at the sendto() call, but all the parameters look good. I'm running the code as root, etc. Is there perhaps a kernel setting that prevents even uid 0 executables from sending packets through raw sockets in OS X Snow Leopard? Thanks.

I may have solved the mystery. I too crafted a raw socket example, which runs fine on Linux, but got "Invalid Argument" error on OS X 10.6.
I encountered this page " FreeBSD socket bugs and peculiarities " while googling for an answer. And it says:

Writing to RAW sockets


- ip_len and ip_off must be in host byte order

So I replace

ip.ip_len = htons(len);

with

ip.ip_len = len;

on OS X. And it works, however strange it is.

user37278, I ran the same program on my Mac OS X (Snow Leopard) and get the same error message. I found the problem is that the custom IP header structure is incoherent with the IP header format. (Might have something to do difference in machines.. I'm not sure).

What I did was I removed his custom IP header structure and used the IP header struct included with Mac OS X. The header information is defined in <netinet/ip.h> and the struct is struct ip . I also found another struct called struct iphdr and I'm not sure the difference.

The headers I included are <netinet/ip.h> <netinet/udp.h> <netinet/in.h> <arpa/inet.h>

Hope this helps.

FreeBSD takes another approach. It never passes TCP or UDP packets to raw sockets. Such packets need to be read directly at the datalink layer by using libraries like libpcap or the bpf API. It also never passes any fragmented datagram. Each datagram has to be completeley reassembled before it is passed to a raw socket.

this might go for OSX as well

Source: http://sock-raw.org/papers/sock_raw

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