一个奇怪的socket问题

有一段代码,将其作为一个函数放入到dll文件时,connect会出现失败,WSAGetLastError返回代码为10060,我查的结果是超时。

http://msdn.microsoft.com/en-us/library/ms740668%28v=vs.85%29.aspx

但我单独写成一个文件,编译成exe文件执行时就可以连接成功。

不知道大家有没有遇到过这种情况?

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <sys/types.h>

#include <winsock2.h>

void wlog(const char* l){
    FILE *f=fopen("log.txt", "a+");
    int le=strlen(l);
    fwrite(l, le, 1, f);
    fclose(f);
} 

 

int iRes=0;
int ret = -1;
int sock = 0;
WORD wVersionReq;
WSADATA wsad;
struct sockaddr_in servername;
int tmpl=sizeof (servername);
wVersionReq=MAKEWORD(2, 0);
iRes=WSAStartup(wVersionReq, &wsad);
if(iRes!=0){
    wlog("sock init err\n");
    WSACleanup();
    return (ret);
}
//init sock
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
wlog("sock init err\n");
    WSACleanup();
return (ret);
}
 
servername.sin_family = AF_INET;
servername.sin_port = htons(port);
servername.sin_addr.S_un.S_addr= inet_addr(host);
/*
//init connect addr
ret = init_sockaddr(&servername, host, port);
if (ret != 0) {
wlog("addr err\n");
    WSACleanup();
return (ret);
}
//*/
 
//*
int itimeout=6000;
if(setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&itimeout, sizeof(itimeout))==SOCKET_ERROR){
    char tmp [10];
    sprintf(tmp, "%d", WSAGetLastError());
    wlog("set sock recv err\n");
    wlog(tmp);
    WSACleanup();
    return (ret);
}
if(setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&itimeout, sizeof(itimeout))==SOCKET_ERROR){
    char tmp [10];
    sprintf(tmp, "%d", WSAGetLastError());
    wlog("set sock send err\n");
    wlog(tmp);
    WSACleanup();
    return (ret);
}
//*/
 
//connect
ret = connect(sock, (struct sockaddr*) &servername, tmpl);
if (ret == SOCKET_ERROR ) {
    char tmp [10];
    sprintf(tmp, "%d", WSAGetLastError());
    wlog("connect err\n");
    wlog(tmp);
    WSACleanup();
    return (ret);
}

你可能感兴趣的:(一个奇怪的socket问题)