- #include <sys/types.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <netdb.h>
- int common_create_server_sock(const char *hostname,const char *port,int sin_family)
- {
- struct addrinfo hints;
- struct addrinfo *result, *rp;
- int iret = 0;
- int sfd = 0;
- memset(&hints, 0, sizeof(struct addrinfo));
- hints.ai_family = AF_UNSPEC; /* IPv4-IPv6 independencies */
- hints.ai_socktype = sin_family;
- hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
- hints.ai_protocol = 0; /* Any protocol */
- iret = getaddrinfo(hostname,port, &hints, &result);
- if(iret != 0)
- {
- fprintf(stderr, "getaddrinfo: %s\\n", gai_strerror(iret));
- return -1;
- }
- for (rp = result; rp != NULL; rp = rp->ai_next)
- {
- sfd = socket(rp->ai_family, rp->ai_socktype,rp->ai_protocol);
- if (sfd == -1)
- {
- continue;
- }
- if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
- {
- break; /* Success */
- }
- close(sfd);
- }
- if (rp == NULL)
- {
- /* No address succeeded */
- fprintf(stderr, "Could not bind\\n");
- return -1;
- }
- freeaddrinfo(result);/*No longer needed */
- listen(sfd,32);
- return sfd;
- }
- int main(int argc, char const *argv[])
- {
- /* code */
- int socket_fd = 0;
- struct sockaddr_storage peer_addr;
- int cfd = 0;
- socket_fd = common_create_server_sock("192.168.0.26","8080",SOCK_STREAM);
- if(socket_fd < 0)
- {
- return 0;
- }
- while(1)
- {
- accept(socket_fd,&peer_addr,sizeof(peer_addr));
- /*recv
- read*/
- }
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/171220138084.html
来源: http://www.codesnippet.cn/detail/171220138084.html