Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

send data to port in c

#define MYPORT 8080


int main(int argc, char *argv[ ]) {

int sockfd;

/* connector’s address information */

struct sockaddr_in their_addr;
struct hostent *he;
int numbytes;

int sockfd2, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];


if (argc != 3) {
    fprintf(stderr, "Usage: %s <hostname> <message>
", argv[0]);
    exit(1);
}

/* get the host info */

if ((he = gethostbyname(argv[1])) == NULL) {
perror("Error obtaining the client. 
");
    exit(1);
}

else printf("Client obtained
");

if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
    perror("Error creating UDP socket
");
    exit(1);
}

else printf("UDP Socket done
");

their_addr.sin_family = AF_INET;

printf("Port: 8080
");

their_addr.sin_port = htons(MYPORT);

their_addr.sin_addr = *((struct in_addr *)he->h_addr);

memset(&(their_addr.sin_zero), '', 8);

 sockfd2 = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd2 < 0) 
    error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
    fprintf(stderr,"ERROR, no such host
");
    exit(0);
}

//sending port where the TCP socket will be associated
//server client connects correctly to this port 
//and the code it's working fine in this point
if((numbytes = sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1)

{

perror("Client-sendto() error lol!");

exit(1);

}
//port is sent, now let's connect to the port by tcp and write the string
//not working properly from now on

bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, 
     (char *)&serv_addr.sin_addr.s_addr,
     server->h_length);
serv_addr.sin_port = htons(atoi(argv[2]));
if (bind(sockfd2,(struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) 
    error("ERROR connecting");

listen(sockfd2, 5);
accept(sockfd2, 0, 0);
printf("accepted!
");

//sending the string to the TCP Port...
if((numbytes = sendto(sockfd2, "hi", 2, 0, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr))) == -1)

{

printf("Client-sendto()-TCP error
");

exit(1);

}


if (close(sockfd) != 0) printf("Client-sockfd-UDP closing is failed!
");
else printf("Client-sockfd-UDP successfully closed!
");
if (close(sockfd) != 0) printf("Client-sockfd2-TCP closing is failed!
");
else printf("Client-sockfd2-TCP successfully closed!
");
return 0;

}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #send #data #port
ADD COMMENT
Topic
Name
2+4 =