1.一段简单的客户服务器程序
[root@liumengli net]# cat client1.c
#include "/programe/net/head.h"
#include "stdio.h"
#include "stdlib.h"
int main(int argc, char ** argv) {
??????? int sockfd, n;
??????? int my;
??????? char buf[100];
??????? struct sockaddr_in servaddr;
??????? if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
??????????????? printf("create socket error\n");
??????????????? exit(1);
??????? }
??????? bzero(&servaddr, sizeof(servaddr));
??????? servaddr.sin_family = AF_INET;
??????? servaddr.sin_port = htons(atoi(argv[2]));
??????? if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) < 0) {
??????????????? printf("inet_pton error\n");
??????????????? exit(1);
??????? }
??????? if((my = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) < 0) {
??????????????? printf("connect error\n");
??????????????? exit(1);
??????? }
??????? n = read(sockfd, buf, 100);
??????? buf[n] = '\0';
??????? printf("%s\n", buf);
??????? printf("%d\n", my);
??????? getchar();
??????? exit(0);
}
[root@liumengli net]# cat head.h
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "netdb.h"
[root@liumengli net]# cat server1.c
#include "/programe/net/head.h"
#include "stdio.h"
#include "stdlib.h"
int main(int argc, char ** argu) {
??????? int listenfd, connfd;
??????? struct sockaddr_in servaddr;
??????? char buf[] = "hello world";
??????? int n;
??????? listenfd = socket(AF_INET, SOCK_STREAM, 0);
??????? bzero(&servaddr, sizeof(servaddr));
??????? servaddr.sin_family = AF_INET;
??????? servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
??????? servaddr.sin_port = htons(atoi(argu[1]));
??????? bind(listenfd, (struct socket_addr *)&servaddr, sizeof(servaddr));
??????? listen(listenfd, n);
??????? for(;;) {
??????????????? connfd = accept(listenfd, (struct socket_addr *)NULL, NULL);
??????????????? write(connfd, buf, strlen(buf));
??????? }
}
?
unix网络编程最简单的例子,这里不做注释了,后面几篇将围绕这个做详细介绍。