linux下,socket网络编程TCP/UDP连接

自己封装了一个函数
int connectsock(char* server_ip, int server_port, int type, int protocolType){
int sock_fd = socket(AF_INET, type, protocolType);
if(-1 == sock_fd){
printf(“create socket error\n”);
return -1;
}
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
inet_pton(AF_INET, server_ip, &server_addr.sin_addr);
printf(“Server IP:%s \n”,server_ip);
printf(“Port:%d \n”,server_port);
if(-1 == connect(sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr))){
printf(“connect server error\n”);
return -1;
}
printf(“connect server success\n”);
return sock_fd;
}

TCP连接:
connectsock(192.168.0.1, 1011, SOCK_STREAM, IPPROTO_TCP);
UDP连接:
connectsock(192.168.0.1, 1011, SOCK_DGRAM, IPPROTO_UDP);

你可能感兴趣的:(C语言)