TCP 日间客户端
这是一个尽可能简单的 TCP 日间客户端。
#include <unistd.h> /* unix standard library */
#include <arpa/inet.h> /* IP addresses manipulation utilities */
#include <netinet/in.h> /* sockaddr_in structure definition */
#include <sys/socket.h> /* berkley socket library */
#include <stdio.h> /* standard I/O library */
#include <string.h> /* include to have memset*/
#include <stdlib.h> /* include to have exit*/
#define MAXLINE 1024
int main(int argc, char *argv[])
{
int sock_fd;
int nread;
struct sockaddr_in serv_add;
char buffer[MAXLINE];
/* socket creation third parameter should be IPPROTO_TCP but 0 is an
* accepted value*/
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
/* address initialization */
memset(&serv_add, 0, sizeof(serv_add)); /* init the server address */
serv_add.sin_family = AF_INET; /* address type is IPV4 */
serv_add.sin_port = htons(13); /* daytime post is 13 */
/* using inet_pton to build address */
inet_pton(AF_INET, argv[1], &serv_add.sin_addr);
/* connect to the server */
connect(sock_fd, (struct sockaddr *)&serv_add, sizeof(serv_add));
/* read daytime from server */
while ((nread = read(sock_fd, buffer, MAXLINE)) > 0)
{
buffer[nread] = 0;
if (fputs(buffer, stdout) == EOF)
{
perror("fputs error"); /* write daytime on stdout */
return -1;
}
}
close(sock_fd);
exit(0);
}