C语言socket入门
socket协议
三次握手与结束连接
客户端代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> //for bzero #include <netinet/in.h> //for socketaddr_in #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #define PORT 5050 //端口号 #define MAXLEN_FOR_DATA 1024//数据的最大长度 int main(){ int clientfd;// 套接字 int len, ret; char buf[MAXLEN_FOR_DATA]; struct sockaddr_in serveraddr; //建立套接口 clientfd = socket(AF_INET, SOCK_STREAM, 0); if (clientfd == -1){ fprintf(stderr, "Failed: socket()\n "); goto exit; } printf("Sucessed: socket()\n"); //****连接******** serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); serveraddr.sin_port = htons(PORT); len = sizeof(serveraddr); ret = connect(clientfd, (struct sockaddr*)&serveraddr, len); if (ret == -1){ fprintf(stderr, "Failed: connect()\n"); goto exit; } printf("Sucessed: connect() \n"); sprintf(buf, "%s \n", "Hello World!"); ret = send(clientfd, (void*)buf, strlen(buf), 0); if (ret <= 0){ fprintf(stderr, "Failed: send()\n"); goto exit; } printf("Sucessed: send()\n"); exit: close(clientfd); clientfd = -1; return 0; }
服务器:
#include <stdio.h> #include <stdlib.h> #include <string.h> //for bzero #include <netinet/in.h> //for socketaddr_in #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #define PORT 5050 #define LEN_FOR_LISTEN_QUEUE 5 #define MAXLEN_FOR_DATA 1024 int main(){ // int serverfd, clientfd;//套接字 int len; int ret; char buf[MAXLEN_FOR_DATA]; struct sockaddr_in serveraddr;//服务器地址信息 struct sockaddr_in clientaddr; //创建套接口 serverfd = socket(AF_INET, SOCK_STREAM, 0); if (serverfd == -1){ fprintf(stderr, "Failed: socket()\n"); goto exit; } printf("Sucessed: socket()\n"); //绑定地址和端口号 serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons(PORT); len = sizeof(serveraddr); ret = bind(serverfd, (struct sockaddr*)&serveraddr, len); if (ret == -1){ fprintf(stderr, "Failed: bind()\n"); goto exit; } printf("Sucessed:bind()\n"); //建立套接口监听队列 ret = listen(serverfd, LEN_FOR_LISTEN_QUEUE); if (ret == -1){ fprintf(stderr, "Failed: listen()\n"); goto exit; } printf("Sucess:listen()\n"); while (1){ printf("Wait For..\n"); fflush(stdout); //接受连接 len = sizeof(clientaddr); clientfd = accept(serverfd, (struct sockaddr*)&clientaddr, &len); if (clientfd == -1){ fprintf(stderr, "Failed: accept()\n"); goto exit; } printf("Sucessed:accept()!\n"); //接受数据 ret = recv(clientfd, (void*)buf, MAXLEN_FOR_DATA, 0); if (ret <= 0){ fprintf(stderr, "Failed: recv()\n"); } else { printf("Sucessed: recv()\n Data:%s", buf); } //关闭连接 close(clientfd); printf("Closed!\n"); } exit: return 0; }