클라이언트 소켓에서 포트를 지정해서 바인딩 해주면 된다.
간단하지만 알아내는 데 한~참 걸렸다.
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main(int argc, char *argv[])
{
if(argc !=4){
printf("Usage : %s <host> <port> <client port>", argv[0]);
return 0;
}
int sockfd;
char *host = argv[1];
int sport = atoi(argv[2]); //Server Port
int cport = atoi(argv[3]); //Client Port
struct sockaddr_in svr, cli;
int recvlen = 0;
int on = 1;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("[Server]Socket Opening Failed!");
return 0;
}
memset(&svr, 0x00, sizeof(svr));
svr.sin_family = AF_INET;
svr.sin_port = htons(sport);
svr.sin_addr.s_addr = inet_addr(host);
memset(&cli, 0x00, sizeof(cli));
cli.sin_family = AF_INET;
cli.sin_port = htons(cport);
cli.sin_addr.s_addr = htonl(0x0f0102fc); // 15.1.2.252
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0){
perror("Set Error");
}
bind(sockfd, (struct sockaddr *)&cli, sizeof(struct sockaddr));
// Connect
if(connect(sockfd, (struct sockaddr *)&svr, sizeof(struct sockaddr)) == -1){
perror("Connect Error in connection!!");
}
printf("Connect!!\t[Server: %s:%d]\n", host, sport);
printf("\t\t[Client: 15.1.2.252:%d]\n", cport);
sleep(100);
close(sockfd);
return 0;
}
댓글 없음:
댓글 쓰기