位置:C:\Users\Administrator\Desktop\C++\SocketYzhi\Win_socket\Win_socket
头文件:
#define _CRT_SECURE_NO_WARNINGS
/* -------------------------------------------------------------------------- */
/* --- DEPENDANCIES --------------------------------------------------------- */#include<iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include<stdio.h>
using namespace std;
#pragma comment(lib,"Ws2_32.lib")
初始化Winsock
// Declare and initialize variables
WSADATA wsaData;
int iResult;// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);if (iResult != 0) {
printf("WSAStartup failed: %d/n", iResult);
return 1;
}
server socket creation
/* server socket creation */
int sock;
struct addrinfo hints;
struct addrinfo *result;
struct addrinfo *q;
char host_name[64];
char port_name[64];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; /* will assign local IP automatically */
主要程序段:
/* try to open socket and bind it */
for (q = result; q != NULL; q = q->ai_next) {sock = socket(q->ai_family, q->ai_socktype, q->ai_protocol);
if (sock == -1) {
continue; /* socket failed, try next field */
}
else {
i = bind(sock, q->ai_addr, q->ai_addrlen);
if (i == -1) {
shutdown(sock, SD_BOTH);
continue; /* bind failed, try next field */
}
else {
break; /* success, get out of loop */
}
}
}
if (q == NULL) {
printf("ERROR: failed to open socket or to bind to it\n");
i = 1;
for (q = result; q != NULL; q = q->ai_next) {
getnameinfo(q->ai_addr, q->ai_addrlen, host_name, sizeof host_name, port_name, sizeof port_name, NI_NUMERICHOST);
printf("INFO: result %i host:%s service:%s\n", i, host_name, port_name);
++i;
}
exit(EXIT_FAILURE);
}
printf("INFO: util_ack listening on port %s\n", argv[1]);
freeaddrinfo(result);
typedef struct addrinfo
{
int ai_flags; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST
int ai_family; // PF_xxx
int ai_socktype; // SOCK_xxx
int ai_protocol; // 0 or IPPROTO_xxx for IPv4 and IPv6
size_t ai_addrlen; // Length of ai_addr
char * ai_canonname; // Canonical name for nodename
_Field_size_bytes_(ai_addrlen) struct sockaddr * ai_addr; // Binary address
struct addrinfo * ai_next; // Next structure in linked list
}
参考链接:
主机名、服务与地址的映射——getaddrinfo(),getnameinfo(),gai_strerror() - 码农 - 优快云博客
https://blog.youkuaiyun.com/duyiwuer2009/article/details/7875206
POSIX-Data Structure - LubinLew - 博客园
http://www.cnblogs.com/LubinLew/p/POSIX-DataStructure.html#struct_addrinfo
getaddrinfo - LubinLew - 博客园
https://www.cnblogs.com/LubinLew/p/POSIX-getaddrinfo.html