发信人: tsingxiao()
整理人: girlrong(1999-11-13 15:15:16), 站内信件
|
第二块砖头 :-)
/* t_cnt's LINUX editon, author: TsingXiao, 1999.07.12 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#define DEF_IP "127.0.0.1" /* default IP */
#define DEF_PORT 5556 /* default port */
#define BUF_LEN 255 /* s_buf's length */
#define STDIN 0 /* standard input */
int ret_no; /* return number */
int port; /* Remote port */
struct hostent* he; /* remote host infos' */
void print_usage();
void print_usage()
{
printf("Usage: cnt [IP address] [port-number]\n");
printf("This small stuff is ONLY a toy! Can execute foreign commands. \n");
printf("You can specify IP and port to connect on.\n");
printf("author: [email protected], 1999\n");
}
main(int argc, char* argv[])
{
int sockfd; /* local socket */
int i;
char s_buf[BUF_LEN];
char cmd_line[BUF_LEN];
struct sockaddr_in addr_in; /* remote addr_in */
he = NULL;
port = -1;
print_usage();
if (argc == 1) {
port = DEF_PORT; /* default port */
he = gethostbyname(DEF_IP);
}
if (argc == 2) {
he = gethostbyname(argv[1]);
}
if (argc == 3) {
he = gethostbyname(argv[1]);
port = atoi(argv[2]);
}
if (he == NULL) {
printf("gethostbyname error, code: %d\nAbort!\n", errno);
exit(-1);
}
if ((port <= 0) || (port > 99999)) {
port = DEF_PORT;
}
printf("IP: %s\n", inet_ntoa(*((struct in_addr *)he->h_addr)));
printf("Port: %d\n", port);
sockfd = socket(AF_INET, SOCK_STREAM, 0); /* do some error checking ! */
if (sockfd < 0) {
printf("socket error, code: %d\nAbort!\n", errno);
exit(-1);
}
addr_in.sin_family = AF_INET; /* host byte order */
addr_in.sin_port = htons(port); /* short, network byte or der */
addr_in.sin_addr = *((struct in_addr *)he -> h_addr);
bzero(&(addr_in.sin_zero), 8); /* zero the rest of the s truct */
ret_no = connect(sockfd, (struct sockaddr *)&addr_in, sizeof(struct s ockaddr));
if (ret_no < 0) {
printf("connect error, code: %d\nAbort!\n", errno);
exit(-1);
}
printf("Enter Cmd: ");
while (1) {
fd_set readfds;
bzero(s_buf, BUF_LEN);
bzero(cmd_line, BUF_LEN);
FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
FD_SET(STDIN, &readfds);
select(sockfd + 1, &readfds, NULL, NULL, NULL);
if (FD_ISSET(sockfd, &readfds)) { /* receive from remote */
ret_no = recv(sockfd, s_buf, BUF_LEN, 0);
if (ret_no < 0) {
printf("recv error, code: %d\nAbort!\n", errno);
exit(-1);
}
printf("\n-*-*-*-*-*-*-\nReceived: %s\n-*-*-*-*-*-*-\n", s_buf);
}
if (FD_ISSET(STDIN, &readfds)) { /* receive from terminal */
read(STDIN, cmd_line, BUF_LEN);
if (cmd_line[0] == 10) {
continue;
}
cmd_line[strlen(cmd_line) - 1] = 0;
ret_no = send(sockfd, cmd_line, strlen(cmd_line), 0);
if (ret_no < 0) {
printf("send error, code: %d\nContinue!\n", errno);
continue;
}
}
}
close(sockfd);
}
-- 我
既不能达而兼善天下
只好穷而独善自身
青山处处 斯民如土矣……
※ 来源:.月光软件站 http://www.moon-soft.com.[FROM: 202.96.243.173]
|
|