标签:
#include <sys/types.h>
#include <sys/socket.h>
int socket(int domain, int type, int protocol);
值 |
说明 |
AF_UNIX |
UNIX内部使用 |
AF_INET |
TCP/IP协议 |
AF_ISO |
国际标准组织协议 |
AF_NS |
Xerox网络协议 |
值 |
说明 |
SOCK_STREAM |
使用TCP可靠连接 |
SOCK_DGRAM |
使用UDP不可靠连接 |
int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen);
int on = 1;
setsockopt(st, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen);
int listen(int sockfd, int backlog);
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen);
ssize_t send(int s, const void *buf, size_t len, int flags);
ssize_t recv(int s, void *buf, size_t len, int flags);
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int arg, char *args[]) { int st = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(8080); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); if(connect(st, (struct sockaddr *)&addr, sizeof(addr)) == -1) { printf("connect failed %s\n", strerror(errno)); return EXIT_FAILURE; } char s[1024]; memset(s, 0, sizeof(1024)); strcpy(s, "hello world"); if(send(st, s, sizeof(s), 0) == -1) { printf("send failed %s\n", strerror(errno)); return EXIT_FAILURE; } close(st); return EXIT_SUCCESS; }
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int arg, char *args[]) { int st = socket(AF_INET, SOCK_STREAM, 0); int on = 1; if (setsockopt(st, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) { printf("setsockopt failed %s\n", strerror(errno)); return EXIT_FAILURE; } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(8080); addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(st, (struct sockaddr *) &addr, sizeof(addr)) == -1) { printf("bind failed %s\n", strerror(errno)); return EXIT_FAILURE; } if (listen(st, 20) == -1) { printf("listen failed %s\n", strerror(errno)); return EXIT_FAILURE; } char s[1024]; int client_st = 0; socklen_t len = 0; struct sockaddr_in client_addr; void *p = &client_addr; int i; for (i = 0; i < 5; i++) { memset(&client_addr, 0, sizeof(client_addr)); socklen_t len = sizeof(client_addr); client_st = accept(st, p, &len); if (client_st == -1) { printf("accept failed %s\n", strerror(errno)); return EXIT_FAILURE; } memset(s, 0, sizeof(1024)); if (recv(client_st, s, sizeof(s), 0) == -1) { printf("recv failed %s\n", strerror(errno)); close(client_st); return EXIT_FAILURE; } printf("revc is %s\n", s); close(client_st); } close(st); return EXIT_SUCCESS; }
标签:
原文地址:http://www.cnblogs.com/shichuan/p/4496310.html