#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#define SERVPORT 3333
#define BACKLOG 10
#define MAX_CONNECTED_NO 100
#define MAXDATASIZE 100
int main()
{
struct sockaddr_in server_sockaddr,client_sockaddr;
int sin_size,recvbytes;
int sockfd,client_fd;
char buf[MAXDATASIZE];
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket");
exit(1);
}
printf("socket success!,sockfd=%d\n",sockfd);
server_sockaddr.sin_family=AF_INET;
server_sockaddr.sin_port=htons(SERVPORT);
server_sockaddr.sin_addr.s_addr=INADDR_ANY;
bzero(&(server_sockaddr.sin_zero),8);
if(bind(sockfd,(struct sockaddr *)&server_sockaddr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
printf("bind success!\n");
while(1){
if((recvbytes=recv(sockfd,buf,MAXDATASIZE,0))==-1)
{
perror("recv");
exit(1);
}
printf("received a connection:%s\n",buf);
}
close(sockfd);
}
#include<sys/types.h>
#include<sys/socket.h>
#include<errno.h>
#include<string.h>
#include<netinet/in.h>
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#define SERVERPORT 3333
#define MAXDATASIZE 100
main(int argc,char *argv[]){
int sockfd,sendbytes;
char buf[MAXDATASIZE];
struct hostent *host;
struct sockaddr_in serv_addr;
if(argc<2)
{
fprintf(stderr,"please enter the server's hostname!\n");
exit(1);
}
if((host=gethostbyname(argv[1]))==NULL)
{
perror("socket");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERVERPORT);
serv_addr.sin_addr=*((struct in_addr *)host->h_addr);
bzero(&(serv_addr.sin_zero),8);
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1)
{
perror("connect");
exit(1);
}
char a[100];
gets(a);
printf("%s\n",a);
printf("%d\n",sizeof(a));
if((sendbytes=send(sockfd,a,sizeof(a),0))==-1){
perror("send");
exit(1);
}
close(sockfd);
}
socket udp server clinet
最新推荐文章于 2021-05-03 12:35:58 发布