简单的TCP-Client
来源:互联网 发布:印刷软件管理 编辑:程序博客网 时间:2024/06/05 09:36
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <errno.h>int main(int argc, char *argv[]){ int sk, ret; char buff[1024] = {'\0'}; struct sockaddr_in server; sk = socket(AF_INET, SOCK_STREAM, 0); if(sk == -1){ printf("%s\n", strerror(errno)); return -1; } server.sin_family = AF_INET; server.sin_port = htons(3000); server.sin_addr.s_addr = inet_addr("192.168.2.8"); ret = connect(sk, (struct sockaddr*)&server, sizeof(server)); if(ret != 0){ printf("%s\n", strerror(errno)); return -1; }#if 0 ret = recv(sk, buff, sizeof(buff), 0); if(ret < 0){ printf("send error\n"); return -1; }else{ printf("the number read %d bytes\n", ret); } printf("%s\n", buff);#endif ret = send(sk, "I am hahaya", strlen("I am hahaya") + 1, 0); if(ret < 0){ printf("send error\n"); return -1; }else{ printf("the number sent %d bytes\n", ret); } close(sk); return 0;}