Labels: Network Programming C language linux socket
Exercise: File Transfer function
First, a function
Int ftruncate (int fd, off_t length)
Function: change the file size specified by fd to the size specified by the parameter length.
Note: fd must be enabled in write mode.
Parameter: fd is the file descriptor of an opened file.
Length specifies the file size.
Return value: 0 is returned for success, and-1 is returned for failure.
The client transmits a file to the server.
Typedef struct
{
Int size; r buf [1024];
Cha
} MSG;
Client:
File name sent for the first time, file size
MSG msg;
Msg. size = file_size;
Strcpy (msg. buf, "file name ");
Send (sockfd, & msg, sizeof (MSG ))
Next Data transmission
Msg. size = read (fd, msg. buf, sizeof (msg. buf ));
Send (sockfd, & msg, sizeof (MSG ))
UDP data sending and receiving functions
Ssize_t recvfrom (int sockfd, void * buf, size_t len, int flags, struct sockaddr * src_addr, socklen_t * addrlen)
Function: receives data.
Parameters:
Socket created by sockfd
Address where the buf receives data
Len expected data size
Flags 0
Src_addr get the sender's address
Addrlen value result parameter (initialization is required before use, and the initial size is the size of struct sockaddr)
Return value:
The number of received bytes is returned. If the number of received bytes fails,-1 is returned.
Ssize_t sendto (int sockfd, void * buf, size_t len, int flags, const struct sockaddr * dest_addr, socklen_t addrlen)
Function: Send data
Parameters:
Socket obtained by sockfd
Data storage address sent by buf
Len expected data size
Flags 0
Dest_addr target host address
Size of the addrlen address (size of the sockaddr struct)
Returned value: the received socket is returned successfully. If the socket fails,-1 is returned.
TC/UDPP network programming