(转)关于gethostname函数失败的问题
参考:http://blog.csdn.net/laowu_/article/details/5461077
MFC socket网络编程(流程示例) 参考:http://www.cnblogs.com/lishennan/p/4362963.html
调用gethostname之前, 要先调用WSAStartup才可以, 否则gethostname会失败!
下面是正确的代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <Winsock2.h> #include <windows.h> #pragma comment(lib, "ws2_32.lib") int main() { WSADATA wsData; ::WSAStartup(MAKEWORD(2,2), &wsData); char szIP[32] = {0}; char szHostName[32] = {0}; int iResult = ::gethostname(szHostName, sizeof(szHostName)); if (iResult != 0) { printf("error\n"); return -1; } printf("%s\n", szHostName); hostent *pHost = ::gethostbyname(szHostName); ::WSACleanup(); return 0; }
运行结果: