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 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).
- }
- size_t get_file_len(int fd){
- size_t len;
- lseek(fd, 0, SEEK_SET); //set at the beginning of your file
- len = lseek(fd, 0, SEEK_END); //lseek() returns number of byte measured
- lseek(fd, 0, SEEK_SET); //set again at the beginning of the file
- return len;
- }
- int main (){
- //define most important socket memebers
- int server_fd; //server file descriptor
- struct sockaddr_in server, client;
- socklen_t addr_size; //
- int fd; //your file descriptor
- char buff[64];
- char file_name[32];
- size_t file_len, size_to_send;
- //CREATE SOCKET
- if ( (server_fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0){
- die("socket()");
- }
- puts("socket()");
- //INITIALIZE SERVER ADDRESS
- server.sin_family = AF_INET;
- server.sin_port = htons(PORT);
- server.sin_addr.s_addr = INADDR_ANY;
- puts("address initialized");
- //BIND ADDRESS AND SOCKET FILE DESCRIPTOR
- addr_size = sizeof(struct sockaddr);
- if ( (bind(server_fd, (struct sockaddr*)&server, addr_size)) < 0){
- die("bind()");
- }
- puts("bind()");
- //RECV FROM CLIENT NAME OF THE FILE YOU WANT TO OPEN
- if ( (recvfrom(server_fd, file_name, sizeof(file_name), 0, (struct sockaddr*)&client, &addr_size)) < 0){
- die("recvfrom");
- }
- printf("Connected with %s at %d port\n", inet_ntoa(client.sin_addr), htons(client.sin_port));
- //OPEN YOUR FILE (IF IT EXISTS) AND THEN CALCULATE IT'S LENGTH AND SEND IT
- if ( (fd = open(file_name, O_RDONLY)) < 0){
- die("open()");
- }
- puts("file opened");
- //GET FILE LEN
- file_len = get_file_len(fd);
- //SEND FILE LENGTH
- if ( (sendto(server_fd, &file_len, sizeof(file_len), 0, (struct sockaddr*)&client, addr_size)) <0 ){
- die("sendto()");
- }
- puts("file length sent");
- //NOW SEND YOUR FILE
- //READ FROM YOUR FILE (fd) AND SAVE sizeof(buff) BYTES TO BUFF
- read(fd, buff, sizeof(buff));
- if ( (size_to_send = sendto(server_fd, buff, strlen(buff), 0, (struct sockaddr*)&client, addr_size)) <0 ){
- die("sendto()");
- }
- puts("file sent");
- //YOUR FILE SHOULD HAVE BEEN SENT SUCCESSFULLY
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement