1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
#include <winsock2.h>
#include <stdio.h>
#include <assert.h>
static void initw (void)
{
WSADATA wsa_data;
WSAStartup (MAKEWORD (2, 2), &wsa_data);
}
static void endw (void)
{
WSACleanup ();
}
SOCKET create_socket_tcp (void)
{
/* open a socket in TCP/IP mode. */
return socket (AF_INET, SOCK_STREAM, 0);
}
int connection_tcp (SOCKET sock, char const *ip, unsigned port)
{
int err = 0;
/* connection data */
SOCKADDR_IN sin = { 0 };
/* server IP address */
sin.sin_addr.s_addr = inet_addr (ip);
/* protocol family (IP) */
sin.sin_family = AF_INET;
/* destination port */
sin.sin_port = htons (port);
/* client connection request (blocking) */
printf ("waiting for a connection to the server on %s:%d...\n", ip, port);
{
int sock_err = connect (sock, (SOCKADDR *) & sin, sizeof sin);
if (sock_err != SOCKET_ERROR)
{
printf ("client connected with socket %d from %s:%d\n",
sock, inet_ntoa (sin.sin_addr), htons (sin.sin_port));
}
else
{
err = 1;
}
}
return 0;
}
static int receive_txt (SOCKET sock)
{
int err = 0;
char buf[1024];
int n = recv (sock, buf, sizeof buf - 1, 0);
if (n > 0)
{
buf[n] = 0;
printf ("%s", buf);
fflush (stdout);
}
else
{
printf ("recv %s\n", n == 0 ? "disconnected" : "error");
err = 1;
}
return err;
}
static void send_txt (SOCKET sock, char const *txt)
{
char buf[1024];
/* commande FTP terminee par CR LF */
int n = sprintf (buf, "%s\r\n", txt);
assert (n < (int) (sizeof buf));
n = send (sock, buf, strlen (buf), 0);
if (n > 0)
{
}
else
{
printf ("send %s\n", n == 0 ? "disconnected" : "error");
}
}
int main (void)
{
char ip[sizeof "xxx.xxx.xxx.xxx"] = "192.168.0.1";
int port = 80;
#if 0
printf ("Entrez Ip \n\n");
scanf ("%s", ip);
printf ("Entrez Port \n\n");
scanf ("%d", &port);
#endif
initw ();
SOCKET Socket = create_socket_tcp ();
int err = connection_tcp (Socket, ip, port);
if (!err)
{
printf ("\nConnecte au serveur %s sur le port %d\n", ip, port);
/* envoi d'une requete basique */
send_txt (Socket, "GET / HTTP 1.0\n");
err = receive_txt (Socket);
}
closesocket (Socket);
endw ();
return 0;
} |
Partager