Okay har lige set din kode. Det er nogen lunde lige så langt jeg er kommet, men der er jo stadig den der 30 sekunder før den mælder tilbage hvis den ikke kan forbinde..
Nå må jeg se om jeg får noget tid i morgen eller lørdag hehe
Så prøv følgende kode, som timer ud efter et sekund:
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
int main(int argc, char ** argv) {
WSADATA wsadata;
SOCKET sock;
struct sockaddr_in address;
DWORD version;
int ret;
u_long non_blocking;
/* Check wheter or not we have enough arguments */
if (argc < 3) {
fprintf(stderr, "Usage: %s <ip address> <port>\n", argv[0]);
return -1;
}
/* Initialize winsock */
version = MAKEWORD(2, 2);
if (WSAStartup(version, &wsadata) != 0) {
fprintf(stderr, "Could not initialize winsock\n");
return -1;
}
/* Create socket */
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
fprintf(stderr, "Could not create socket.\n");
WSACleanup();
return -1;
}
/* Make socket non-blocking */
non_blocking = 1;
if (ioctlsocket(sock, FIONBIO, &non_blocking) == SOCKET_ERROR) {
fprintf(stderr, "Could not make socket non-blocking.\n");
closesocket(sock);
WSACleanup();
return -1;
}
/* Build connect address */
address.sin_addr.S_un.S_addr = inet_addr(argv[1]);
address.sin_family = AF_INET;
address.sin_port = htons(atoi(argv[2]));
/* Try to connect */
ret = connect(sock, (struct sockaddr*)&address, sizeof(struct sockaddr_in));
if (ret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) {
/* This means that we have a non-blocking socket that MAY connect soon */
fd_set writeset;
fd_set errset;
struct timeval timeout;
timeout.tv_sec = 1; /* Wait one second */
timeout.tv_usec = 0; /* ...and zero microseconds */
/* Initialize sets */
FD_ZERO(&writeset);
FD_ZERO(&errset);
/* Add socket to sets */
FD_SET(sock, &writeset);
FD_SET(sock, &errset);
if (select(1, NULL, &writeset, &errset, &timeout) < 1) {
fprintf(stderr, "We got no reply within our time limit.");
ret = -1;
} else if (FD_ISSET(sock, &errset)) {
fprintf(stderr, "We got an error trying to connect. Probably the service did not accept our connection.");
ret = -1;
} else if (FD_ISSET(sock, &writeset)) {
printf("Yay, we got our connection.");
ret = 0;
}
}
closesocket(sock);
WSACleanup();
return ret;
}