Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * uclient.c
- *
- * Created on: Mar 14, 2013
- * Author: none
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <errno.h>
- #define PORT 3666
- void addr_init(struct sockaddr_in *addr, int port, const char *IP){
- addr->sin_family = AF_INET;
- addr->sin_port = htons(port);
- inet_pton(AF_INET, IP, (void*)&addr->sin_addr);
- }
- void die(const char *type_error){
- printf("Error \"%s\" in %s\n", strerror(errno), type_error);
- exit(1); //Remember: exit doesn't terminate current function but the entire program (closing and saving each file descriptor).
- }
- int main (int argc, char **argv){
- /*
- * Create principal socket members
- */
- int client_fd;
- struct sockaddr_in server;
- socklen_t addr_size = sizeof(struct sockaddr);
- char buff_to_read[64]; //buff you'll use to read from server
- char *file_name; //a pointer to argv[2], your file name
- size_t size_to_read = 0, size_read = 0;
- if (argc < 3){
- printf("Usage: <%s><IP-dest><FILE name>\n", argv[0]);
- exit(1);
- }
- if ( (client_fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0){
- die("socket()");
- }
- puts("socket()");
- server.sin_family = AF_INET;
- server.sin_port = htons(PORT);
- server.sin_addr.s_addr = inet_addr(argv[1]);
- file_name = argv[2];
- //SEND TO SERVER YOUR FILE NAME
- if ( (sendto(client_fd, file_name, strlen(file_name), 0, (struct sockaddr*)&server, addr_size)) < 0 ){
- printf("Error \"%s\" in sendto()\n", strerror(errno));
- exit(1);
- }
- puts("file name sent");
- //RECV FROM SERVER YOUR FILE SIZE
- if ( (recvfrom(client_fd, (size_t*)&size_to_read, sizeof(size_to_read), 0, NULL, NULL)) < 0){
- printf("Error \"%s\" in recvfrom()\n", strerror(errno));
- exit(1);
- }
- printf("Size of file: %lu\n", size_to_read);
- //IF FILE SIZE < 0: ERROR, EXIT(1)
- if (size_to_read < 0){
- printf("size_to_read < 0\n");
- exit(1);
- }
- //This commented region doesn't work, but meanwhile I'll try to fix it.
- /*
- *
- //READ UNTIL YOUR FILE SIZE IS > 0
- //size_to_read = length of the message that is going to be sent from server
- //size_read = length of each message received from server on each iteration
- while (size_to_read > 0){
- if ( (size_read = recvfrom(client_fd, buff_to_read, sizeof(buff_to_read), 0, NULL, NULL)) < 0){
- printf("Error \"%s\" in recvfrom()\n", strerror(errno));
- exit(1);
- }
- size_to_read -= size_read;
- }*/
- if ( (size_read = recvfrom(client_fd, buff_to_read, sizeof(buff_to_read), 0, NULL, NULL)) < 0){
- printf("Error \"%s\" in recvfrom()\n", strerror(errno));
- exit(1);
- }
- puts("file received");
- puts(buff_to_read);
- close(client_fd);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement