Jeg har lige hakket følgende program sammen:
#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;
/* 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;
}
/* 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 */
if (connect(sock, (struct sockaddr*)&address, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
fprintf(stderr, "Could not connect\n");
} else {
printf("Connected sucessfully!\n");
}
closesocket(sock);
WSACleanup();
return 0;
}
Det forsøger at oprette en forbindelse til den specificerede IP adresse og port og fortæller, om det gik godt:
C:\Documents and Settings\Robert Larsen\Dokumenter\Projects\connect\bin\Debug>connect 192.168.2.2 80
Connected sucessfully!
C:\Documents and Settings\Robert Larsen\Dokumenter\Projects\connect\bin\Debug>connect 192.168.2.2 60
Could not connect
C:\Documents and Settings\Robert Larsen\Dokumenter\Projects\connect\bin\Debug>
I det ovenstående kunne jeg forbinde til min router på port 80 men ikke port 60.