基本tcp套接字编程。
客户端程序:client.c
- #include <stdio.h>
- #include <unistd.h>
- #include <strings.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #include <stdlib.h>
- #define PORT 1234
- #define MAXDATASIZE 100
- int main(int argc, char **argv)
- {
- int sockfd, num;
- char buf[MAXDATASIZE];
- struct hostent *he;
- struct sockaddr_in server;
- if(argc != 2)
- {
- printf("Uage: %s <IP ADDRESS>/n", argv[0]);
- exit(1);
- }
- if((he = gethostbyname(argv[1])) == NULL)
- {
- printf("gethostbyname() error!");
- exit(1);
- }
- if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
- {
- printf("socket() error.");
- exit(1);
- }
- bzero(&server, sizeof(server));
- server.sin_family = AF_INET;
- server.sin_port = htons(PORT);
- server.sin_addr = *((struct in_addr *)he -> h_addr);
- if(connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1)
- {
- printf("connect() error/n");
- exit(1);
- }
- if((num = recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
- {
- printf("revc() error!/n");
- exit(1);
- }
- buf[num - 1] = '/0';
- printf("server message: %s/n", buf);
- close(sockfd);
- }
服务器端程序:server.c
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <stdlib.h>
- #define PORT 1234
- #define BACKLOG 1
- int main(int argc, char **argv)
- {
- int listenfd, connectfd;
- struct sockaddr_in server;
- struct sockaddr_in client;
- socklen_t addrlen;
- if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
- {
- perror("socket error()!");
- exit(1);
- }
- int opt = SO_REUSEADDR;
- setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
- bzero(&server, sizeof(server));
- server.sin_family = AF_INET;
- server.sin_port = htons(PORT);
- server.sin_addr.s_addr = htonl(INADDR_ANY);
- if(bind(listenfd, (struct sockaddr *)&server, sizeof(server)) == -1)
- {
- perror("Bind() error!");
- exit(1);
- }
- if(listen(listenfd, BACKLOG) == -1)
- {
- perror("listen() error!");
- exit(1);
- }
- addrlen = sizeof(client);
- if((connectfd = accept(listenfd, (struct sockaddr *)&client, &addrlen)) == -1)
- {
- perror("accept() error./n");
- exit(1);
- }
- printf("You got a connection from client's ip is %s, port is %d/n", inet_ntoa(client.sin_addr), htons(client.sin_port));
- send(connectfd, "WELCOME!/n", 10, 0);
- close(connectfd);
- close(listenfd);
- }