#include <stdio.h>
#include <winsock2.h>
#include <time.h>
#define SENDBUF_LEN 100
#define RECVBUF_LEN 100
int main(int argc, char *argv[])
{
WSADATA wsaData;
int cfd;
struct sockaddr_in addr;
char *ip;
short port;
char sendbuf[SENDBUF_LEN];
char recvbuf[RECVBUF_LEN];
int recvlen=0;
fd_set rfds, wfds;
struct timeval timeout;
int S=0;
timeout.tv_sec=1;
timeout.tv_usec=0;
if (argc != 3) {
printf("Usage:\n\t%s server_ip server_port\n"
, argv[0]);
return -1;
}
ip = argv[1];
port = (short)atoi(argv[2]);
WSAStartup(0x0101, &wsaData);
if ( (cfd = socket(AF_INET, SOCK_STREAM, 0) < 0){
printf("Cannot create socekt\n");
return -1;
}
memset(&addr, 0x00, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip);
if ( connect(cfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) < 0) {
printf("Cannot connect to %s\n", ip);
closesocket(cfd);
return -1;
}
FD_ZERO(&wfds);
FD_SET((unsigned int)cfd, &wfds);
if ( select(cfd+1, NULL, &wfds, NULL, &timeout) <=0) {
printf("select fail\n");
return -1;
}
sprintf(sendbuf, "GET / HTTP/1.0\r\n");
if (send(cfd, sendbuf, strlen(sendbuf), 0) < 0) {
printf("Cannot send\n");
closesocket(cfd);
return -1;
}
srand(time(NULL));
while (S < 2000) {
int s=0;
while (s < sizeof(sendbuf)) {
sendbuf[s++] = (char)rand();
}
if (send(cfd, sendbuf, sizeof(sendbuf), 0) < 0) {
printf("Cannot send\n");
closesocket(cfd);
return -1;
}
S += s;
}
sprintf(sendbuf, "\r\n\r\n");
if (send(cfd, sendbuf, strlen(sendbuf), 0) < 0) {
printf("Cannot send\n");
closesocket(cfd);
return -1;
}
FD_ZERO(&rfds);
FD_SET((unsigned int)cfd, &rfds);
if ( select(cfd+1, &rfds, NULL, NULL, &timeout) <=0) {
printf("select fail\n");
return -1;
}
if ( (recvlen=recv(cfd, recvbuf, strlen(recvbuf), 0)) < 0) {
printf("Cannot recv\n");
closesocket(cfd);
return -1;
}
recvbuf[recvlen]=0x00;
printf("%s", recvbuf);
return 0;
}
Monday, June 04, 2007
Windows Socket
The project must be setting to link wsock32.lib or ws2_32.lib. The difference between them I know is ws2_32.lib supports select function, but the other doesn't.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment