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
|
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#define SOCKET_ERROR -1
#define BUFSIZE 4096
int main(int argc, char **argv)
{
int sockfd, portno=3000, protocol;
struct sockaddr_in server;
struct hostent *hp;
char *hostname;
hostname = "127.0.0.1";
protocol = SOCK_STREAM;
sockfd = socket(AF_INET, protocol, 0);
if (sockfd < 0) exit(1);
server.sin_family = AF_INET;//connect socket using hostname
hp = gethostbyname(hostname);
if (hp == 0) exit(1);
memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);
server.sin_port = htons((unsigned short)portno); //assign client port number
connect(sockfd,(struct sockaddr *) &server, sizeof (server));//connect
while (1) //now loop reading stdin and sending it to socket
{
char buf[BUFSIZE], *bp, nsent, nsend;
fgets(buf, BUFSIZE, stdin);
nsend = strlen(buf);
for (bp = buf, nsent = 0; nsent < nsend;)
{
int res = send(sockfd, buf, nsend-nsent, 0);
if (res < 0) exit(1);
send(sockfd, ";", 1, 0);
nsent += res;
bp += res;
}
}
} |
Partager