演示一下 Unix 系统的 C 程序中如何将 Socket 映射到标准IO。
/* sock2stdio.c
* Heiher <admin@heiher.info>
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(int argc, char * argv[])
{
int sock, client, addrlen;
struct sockaddr_in this_addr, peer_addr;
unsigned short port = 9000;
pid_t cpid;
addrlen = sizeof(struct sockaddr_in);
memset(&this_addr, 0, addrlen);
memset(&peer_addr, 0, addrlen);
this_addr.sin_port = htons(port);
this_addr.sin_family = AF_INET;
this_addr.sin_addr.s_addr = htonl(INADDR_ANY);
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
bind(sock, (struct sockaddr*)&this_addr, addrlen);
listen(sock, 5);
while(-1 != (client=accept(sock, (struct sockaddr*)&peer_addr, &addrlen)))
{
cpid = fork();
if(0 > cpid)
{
perror("fork() failed!");
return 1;
}
else if(0 == cpid) /* child */
{
close(0);
close(1);
close(2);
dup2(client, 0);
dup2(client, 1);
dup2(client, 2);
close(client);
execl("/bin/dd", "/bin/dd", "bs=1", NULL);
return 0;
}
}
return 0;
} |
/* sock2stdio.c
* Heiher <admin@heiher.info>
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(int argc, char * argv[])
{
int sock, client, addrlen;
struct sockaddr_in this_addr, peer_addr;
unsigned short port = 9000;
pid_t cpid;
addrlen = sizeof(struct sockaddr_in);
memset(&this_addr, 0, addrlen);
memset(&peer_addr, 0, addrlen);
this_addr.sin_port = htons(port);
this_addr.sin_family = AF_INET;
this_addr.sin_addr.s_addr = htonl(INADDR_ANY);
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
bind(sock, (struct sockaddr*)&this_addr, addrlen);
listen(sock, 5);
while(-1 != (client=accept(sock, (struct sockaddr*)&peer_addr, &addrlen)))
{
cpid = fork();
if(0 > cpid)
{
perror("fork() failed!");
return 1;
}
else if(0 == cpid) /* child */
{
close(0);
close(1);
close(2);
dup2(client, 0);
dup2(client, 1);
dup2(client, 2);
close(client);
execl("/bin/dd", "/bin/dd", "bs=1", NULL);
return 0;
}
}
return 0;
}
gcc -o sock2stdio sock2stdio.c
./sock2stdio |
gcc -o sock2stdio sock2stdio.c
./sock2stdio
nc localhost 9000
hello # Input
hello # Output |
nc localhost 9000
hello # Input
hello # Output
Over!