C Programing - sending a file by using UDP segment over UDP socket.
/* Simple udp client */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #define SERVER "129.120.151.95" #define BUFLEN 512 //Max length of buffer #define PORT 6700 //The port on which to send data void die(char *s) { perror(s); exit(1); } int main(void) { struct sockaddr_in si_other; int sockfd, i=0, slen=sizeof(si_other); char buf[BUFLEN]; char message[BUFLEN]; if ( (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { die("socket"); } memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); if (inet_aton(SERVER , &si_other.sin_addr) == 0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } while(1) { //Clear the message buffer and accept the message to be sent printf("Enter message: "); bzero(message, sizeof(message)); do { message[i] = getchar(); i++; } while (message[i-1] != '\n'); i = 0; //send the message if (sendto(sockfd, message, strlen(message), 0, (struct sockaddr *) &si_other, slen) == -1) { die("sendto()"); } //receive a reply and print it //clear the buffer by filling null, it might have previously received data bzero(buf, sizeof(buf)); //try to receive some data, this is a blocking call if (recvfrom(sockfd, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1) { die("recvfrom()"); } printf("Received message from the server: "); printf("%s\n", buf); } close(sockfd); return 0; }