简体   繁体   中英

What is the simplest way to write to an ip address from within a C program?

I am upgrading a filter program written in C. The program is meant to receive a data-stream from a serial port modify it slightly; then send it on to the ip address of a tcp to rs485 wireless tunnel. Currently the program relies on i/o redirection from a shell script -- it is evoked like this:

./packetfilter </dev/ttyS4 >/dev/tcp/10.0.50.101/4660  

The shell gives me tcp/ip for free. Now I need both stderr and stdout.
What is the simplest way to write my serial data to a network address?

It's very easy to open a socket in C, but most code you find is using ugly, deprecated methods that make it look hard. Here's the correct way:

struct addrinfo *ai;
int fd;
if (getaddrinfo(host_string, port_string, 0, &ai)) goto failed;
fd = socket(ai->ai_family, SOCK_STREAM, 0);
if (connect(fd, ai->ai_addr, ai->ai_addrlen)) goto failed2;

Fill in the error handling.

You need to split the IP address at the "dots", and form a 32-bit integer (assuming that you're only worried about IPV4 - if IPV6, you have more work ahead of you...).

Each "dotted" number will become one byte in yout IP addr5ess - so that in hexadecimal, your address in the example will become 0x0A003265

(0x0A = 10, 00=0, 0x32=50, 0x65=101, if I didn't screw up)

THEN pass the 32 bit integer throputh the htons function so that it is put "in the correct" (network) order (htons converts from host to network byte order). Plug the result into your socket, and you're all set.

重定向到更高的FD,然后使用write(2)

./packetfilter </dev/ttyS4 3>/dev/tcp/10.0.50.101/4660  

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