????Socket??????
????????????е?????????socket??????????????????"Hello?? you are connected!"????????????????и÷???????????????????п?????????????????????????
?????÷???????????????£?
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 3333 /*?????????????? */
#define BACKLOG 10 /* ?????????????? */
main()
{
int sockfd??client_fd; /*sock_fd??????socket??client_fd?????????socket */
struct sockaddr_in my_addr; /* ?????????? */
struct sockaddr_in remote_addr; /* ?????????? */
if ((sockfd = socket(AF_INET?? SOCK_STREAM?? 0)) == -1) {
perror("socket?????????"); exit(1);
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero)??8);
if (bind(sockfd?? (struct sockaddr *)&my_addr?? sizeof(struct sockaddr)) == -1) {
perror("bind?????");
exit(1);
}
if (listen(sockfd?? BACKLOG) == -1) {
perror("listen?????");
exit(1);
}
while(1) {
sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd?? (struct sockaddr *)&remote_addr?? &sin_size)) == -1) {
perror("accept????");
continue;
}
printf("received a connection from %s "?? inet_ntoa(remote_addr.sin_addr));
if (!fork()) { /* ????????? */
if (send(client_fd?? "Hello?? you are connected! "?? 26?? 0) == -1)
perror("send?????");
close(client_fd);
exit(0);
}
close(client_fd);
}
}
}
???????????????????????????????????socket???????????Socket????????bind????????????????????????????????????? listen???????socket?????????accpet????????????????????????????????μ?socket???????????????????IP?????????? ?μ?socket??????????????"Hello??you are connected!"???????socket??
????????????е?fork()????????????????????????????????fork()?????????????????0?????????fork??????if????????????????????if????????????????????????е??
??????????????????£?
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 3333
#define MAXDATASIZE 100 /*??δ?????????? */
main(int argc?? char *argv[]){
int sockfd?? recvbytes;
char buf[MAXDATASIZE];
struct hostent *host;
struct sockaddr_in serv_addr;
if (argc < 2) {
fprintf(stderr??"Please enter the server"s hostname! ");
exit(1);
}
if((host=gethostbyname(argv[1]))==NULL) {
herror("gethostbyname?????");
exit(1);
}
if ((sockfd = socket(AF_INET?? SOCK_STREAM?? 0)) == -1){
perror("socket?????????");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERVPORT);
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);
}
if ((recvbytes=recv(sockfd?? buf?? MAXDATASIZE?? 0)) ==-1) {
perror("recv?????");
exit(1);
}
buf[recvbytes] = "