Reputation: 11
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?
Upvotes: 1
Views: 337
Reputation: 215487
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.
Upvotes: 3
Reputation: 11
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.
Upvotes: 1
Reputation: 799200
Redirect to a higher FD, then use write(2)
.
./packetfilter </dev/ttyS4 3>/dev/tcp/10.0.50.101/4660
Upvotes: 0