#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096
void dg_echo(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen)
{
char buffer[MAXLINE];
int n;
socklen_t len;
memset(buffer, 0, MAXLINE);
while(1)
{
len = clilen;
n = recvfrom(sockfd, buffer, MAXLINE, 0, pcliaddr, &len);
printf("%s\n", buffer);
sendto(sockfd, buffer, n, 0, pcliaddr, len);
memset(buffer, 0, MAXLINE);
}
}
int main()
{
int sockfd;
struct sockaddr_in server_sockaddr, client_sockaddr;
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
fprintf(stderr, "Socket failed\n");
exit(EXIT_FAILURE);
}
bzero(&server_sockaddr, sizeof(server_sockaddr));
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_port = htons(9877);
server_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr*)&server_sockaddr, sizeof(server_sockaddr)) < 0)
{
fprintf(stderr, "Bind failed\n");
exit(EXIT_FAILURE);
}
dg_echo(sockfd, (struct sockaddr*)&client_sockaddr, sizeof(client_sockaddr));
exit(0);
}
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096
void dg_cli(FILE *fp, int sockfd, const struct sockaddr *pservaddr, socklen_t servlen)
{
int n;
char send_buffer[MAXLINE], recv_buffer[MAXLINE+1];
if(connect(sockfd, (struct sockaddr*)pservaddr, servlen) < 0)
{
fprintf(stderr, "Connect failed\n");
exit(EXIT_FAILURE);
}
while(fgets(send_buffer, MAXLINE, fp) != NULL)
{
write(sockfd, send_buffer, strlen(send_buffer));
n = read(sockfd, recv_buffer, MAXLINE);
recv_buffer[n] = 0;
fputs(recv_buffer, stdout);
}
}
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in server_sockaddr;
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
fprintf(stderr, "Socket failed\n");
exit(EXIT_FAILURE);
}
else
printf("Socket success\n");
bzero(&server_sockaddr, sizeof(server_sockaddr));
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_port = htons(9877);
inet_pton(AF_INET, argv[1], &server_sockaddr.sin_addr);
dg_cli(stdin, sockfd, (struct sockaddr*)&server_sockaddr, sizeof(server_sockaddr));
}