473,657 Members | 2,449 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with Select

Hi,

I am trying to use the select() socket programming command to select between
stdin and a connection. Currently, I have a listening stream and stdin that
I insert into the fd_set. The problem is that when I recognize FD_ISSET from
stdin, I am stuck there. The loop does not return me to select() between
stdin and listening socket. Similarly, when I accept a client, the loop does
not return me to select between stdin and listeing socket. I don't know what
to do. I want to be able to select continuously between stdin and the
listening port after I have either accepted from a port or from stdin.

I have pasted the codes that I am using for the listening to port and stdin
and the code for the client.

Please help.

Thank you,

Marcia Hon

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#define max(a, b) ((a) > (b) ? a: b)

int flushToEndOfLin e();

int main(int argc, char *argv[])

{

fd_set master;
struct sockaddr_in myaddr;

struct sockaddr_in remoteaddr;
int fdmax;

int listenerSocket;

int newfd;

char buf[256];

int yes = 1;

int addrlen;

int i, j;
if(argc != 2)

{

fprintf(stderr, "Usage: %s <listen_port>\n ", argv[0]);

exit(1);

}
FD_ZERO(&master ); //clear master set
// get listenerSocket

if((listenerSoc ket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

perror("socket" );

exit(1);

}
// lose socket already in use error message

if(setsockopt(l istenerSocket, SOL_SOCKET, SO_REUSEADDR, &yes,

sizeof(int)) == -1) {

perror("setsock opt");

exit(1);

}
// bind

myaddr.sin_fami ly = AF_INET;

myaddr.sin_addr .s_addr = INADDR_ANY;

myaddr.sin_port = htons(atoi(argv[1]));

memset(&(myaddr .sin_zero), '\0', 8);

if(bind(listene rSocket, (struct sockaddr *) &myaddr, sizeof(myaddr)) == -1)
{

perror("bind");

exit(1);

}
// listen

if(listen(liste nerSocket, 5) == -1) {

perror("listen" );

exit(1);

}
FD_SET(listener Socket, &master);

FD_SET(0, &master);
fdmax = max(listenerSoc ket, 0);
while(1){

printf("select\ n");

if(select(fdmax +1, &master, NULL, NULL, NULL) == -1){

perror("select" );

exit(1);

}
if(FD_ISSET(lis tenerSocket, &master)){

addrlen = sizeof(remotead dr);

if((newfd = accept(listener Socket, (struct

sockaddr *)&remoteaddr, &addrlen)) == -1) {

perror("accept" );

}

printf("new connection from client\n");

close(newfd);

}

else

{

if(FD_ISSET(0, &master))

{

printf("user entered data \n");

flushToEndOfLin e();

}

}

}
return 0;

}

int flushToEndOfLin e()

{

int c;

while ( (c=getchar()) != EOF && c != '\n' );

return;

}

client:

//WHAT IF SHORT IS NOT 2 BYTES?!?!?!?

#include <stdio.h>

#include <stdlib.h>

#include <sys/socket.h>

#include <sys/types.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <netdb.h>

#define FILE_TBYTES 4 //bytes at the beginning of file that specify how many
bytes are in this block being sent

#define MAX_BYTES 1000 //breaks up file into this many bytes and sends this
many bytes at a time

#define MAX_BSEND_RETRY 3 //how many times to retry sending a block of
MAX_BYTES before fail

#define DEBUG

//prototypes

int establish_conne ction (const char * name, unsigned short port);

int send_stream (int sockfd, const char * data, int len);

unsigned long getFileSize(cha r *fileName);

//check ip or dns

int main(int argc, char *argv[])

{

FILE *fp;

int j; //loop counters

short int i; //this better be 2 bytes

char * buffer;

unsigned long *tmp;

unsigned short port;

int sockfd;

unsigned long fileSize;
if ((buffer = (char *) malloc (MAX_BYTES)) == NULL)

{

fprintf(stderr, "Not enough memory for a file input buffer of %d\n",
MAX_BYTES);

exit(1);

}
//Check if 3 arguments passed

if (argc !=4)

{

fprintf(stderr, "Usage: %s <ip> <port> <file>\n", argv[0]);

exit(1);

}
//no check!

port = atoi(argv[2]);
#ifdef DEFINE

printf("Argumen ts Passed:\n");

printf("IP: %s\n", argv[1]);

printf("PORT: %d\n", port);

printf("FILE: %s\n", argv[3]);

printf("\n");

#endif

//open file

if ((fp = fopen(argv[3],"r")) == NULL)

{

fprintf(stderr, "Error: Could not open %s\n", argv[3]);

exit(1);

}
if ((sockfd = establish_conne ction (argv[1], port)) == -1)

{

fprintf(stderr, "Error establishing connection\n");

fclose(fp);

exit(1);

}
//buffer = "Hello World";

//send_stream(soc kfd, buffer, 11);
//send file size

fileSize = getFileSize(arg v[3]);

tmp = (unsigned long *) &buffer[0];

*tmp = (unsigned long) htonl(fileSize) ;

send_stream(soc kfd, buffer, 4);

printf("File Size: %d\n", fileSize);
while (!feof(fp))

{

//read some bytes

for (i = 0; i<MAX_BYTES; i++)

{

buffer[i] = fgetc(fp);

if (feof(fp)) //end of file true

break;

}

//echo bytes to screen

for (j=0; j<i; j++)

{

//put send function here

//printf("%c", buffer[j]);

}
if (!send_stream(s ockfd, buffer, i))

{

fprintf(stderr, "Error sending a block\n");

exit(1);

}

}
//close file

fclose(fp);

close(sockfd);
return 0; //exited succesfully

}

//pass name of the host and port number only!

//-1 fail, sockfd success

int establish_conne ction (const char * name, unsigned short port)

{

struct sockaddr_in their_addr;

int sockfd;

int r; //returned from functions

struct hostent * h;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
//set up the structure

their_addr.sin_ family = AF_INET;

their_addr.sin_ port = htons(port); // short, network byte order

memset(&(their_ addr.sin_zero), '\0', 8); // zero the rest of the struct
h=gethostbyname (name);

if (h == NULL)

return -1;
//1. make *h_addr_list[0] be a in_addr *

//2. dereference this pointer and assign it to their_addr.sin_ addr

their_addr.sin_ addr = *((struct in_addr *)h->h_addr);
printf("IP Address : %s\n", inet_ntoa(*((st ruct in_addr *)h->h_addr)));

printf("IP Address : %s\n", inet_ntoa(their _addr.sin_addr) );

printf("Port: %d \n", ntohs(their_add r.sin_port));
if((connect(soc kfd, (struct sockaddr *) &their_addr, sizeof(struct
sockaddr))) == -1)

return -1;
return sockfd;

}

//sends data

//connect may return that it sent less, this function sends the rest

//return 0 on fail, 1 on success

int send_stream (int sockfd, const char * data, int len)

{

int bytes_sent, newlen;

const void * newdata;
bytes_sent = send(sockfd, data, len,0);

if (bytes_sent < 0)

return 0;

while (bytes_sent < len - 1)

{

//if we sent 10 bytes, we sent bytes 0...9

//need to send byte 10...

newdata = &data[bytes_sent];

bytes_sent = send(sockfd, newdata, len - bytes_sent, 0);

if (bytes_sent < 0)

return 0;

}

return 1;

}

unsigned long getFileSize(cha r *fileName)

{

unsigned long fileSize;

FILE *f=fopen(fileNa me, "rb");

if(f==NULL)

{

fprintf(stderr, "Cannot open file.\n");

exit(EXIT_FAILU RE);

}

else

{

if(fseek(f, 0, SEEK_END)!=0)

{

fprintf(stderr, "Cannot use file.\n");

exit(EXIT_FAILU RE);

}

fileSize=ftell( f);

}

if(fclose(f)!=0 )

{

fprintf(stderr, "Cannot close file.\n");

exit(EXIT_FAILU RE);

}

return fileSize;

}
Nov 14 '05 #1
3 4428
Hi,

Problem fixed! I put FD_SET, FD_CLR, select, FD_ISSET all inside the loop.

Thanks for your help.
Marcia
Nov 14 '05 #2
On Sat, 14 Feb 2004 15:42:52 GMT, "Marcia Hon" <ho**@rogers.co m>
wrote:

This has nothing to do with ANSI C, so I've removed it from the
Followup-To field. (I should probably have removed
comp.os.linux.n etworking, too.)

while(1){

printf("select \n");

if(select(fdma x+1, &master, NULL, NULL, NULL) == -1){

perror("select ");

exit(1);

}


select() will destroy the "master" parameter each time you call it. So
your code should look like this:
saved_master = master;

while(1){
printf("select\ n");

master = saved_master;

if(select(fdmax +1, &master, NULL, NULL, NULL) == -1){
perror("select" );
exit(1);
}
BTW, your code is ugly indented. If the bug in your code hadn't been
easy to spot, probably none would have taken the time to have a look
at it.

--
Fernando Gont
e-mail: fe******@ANTISP AM.gont.com.ar

[To send a personal reply, please remove the ANTISPAM tag]
Nov 14 '05 #3
"Marcia Hon" <ho**@rogers.co m> writes:
I am trying to use the select() socket programming command to select between
stdin and a connection. Currently, I have a listening stream and stdin that
I insert into the fd_set. The problem is that when I recognize FD_ISSET from
stdin, I am stuck there. The loop does not return me to select() between
stdin and listening socket. Similarly, when I accept a client, the loop does
not return me to select between stdin and listeing socket. I don't know what
to do. I want to be able to select continuously between stdin and the
listening port after I have either accepted from a port or from stdin.


Select modifies its arguments. You need to put the FD_SET invocations
*inside* the loop, or save a copy of 'master' somewhere.

--
James Carlson, IP Systems Group <ja************ *@sun.com>
Sun Microsystems / 1 Network Drive 71.234W Vox +1 781 442 2084
MS UBUR02-212 / Burlington MA 01803-2757 42.497N Fax +1 781 442 1677
Nov 14 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3123
by: netpurpose | last post by:
I need to extract data from this table to find the lowest prices of each product as of today. The product will be listed/grouped by the name only, discarding the product code - I use SUBSTRING(ProductName, 1, CHARINDEX('(', ProductName)-2). I can get this result, but I had to use several views (totally inefficient). I think this can be done in one efficient/fast query, but I can't think of one. In the case that one query is not...
28
3296
by: stu_gots | last post by:
I have been losing sleep over this puzzle, and I'm convinced my train of thought is heading in the wrong direction. It is difficult to explain my circumstances, so I will present an identical make-believe challenge in order to avoid confusing the issue further. Suppose I was hosting a dinner and I wanted to invite exactly 12 guests from my neighborhood. I'm really picky about that... I have 12 chairs besides my own, and I want them all...
7
3594
by: x muzuo | last post by:
Hi guys, I have got a prob of javascript form validation which just doesnt work with my ASP code. Can any one help me out please. Here is the code: {////<<head> <title>IIBO Submit Page</title> </head> <style type="text/css">
5
2985
by: Craig Keightley | last post by:
Please help, i have attached my page which worksin IE but i cannnot get the drop down menu to fucntion in firefox. Any one have any ideas why? Many Thanks Craig <<<<<<<<<<<<<<CODE>>>>>>>>>>>>>>>> <html>
0
1971
by: Pat Patterson | last post by:
I'm having serious issues with a page I'm developing. I just need some simple help, and was hoping someone might be able to help me out in here. I have a form, that consists of 3 pages of fields. I'd like to create a page in which all of this is stored as you move along as hidden variables, until the end, when the user submits. I can't figure out one thing: I have dynamic form elements (dropdowns), that I'd like to use instead of...
0
19575
by: JonathanParker | last post by:
Hello, Wondered if you could help me with a little issue I'm having. I'm exporting some data from Access to Excel and converting into some fancy graphs. The number of series' ranges from 2 to 5. Below isa copy of the code I am using to format the graph in terms of series names, layout, colours of lines, etc. When the full 5 series are there to be charted there is no problem with the code, however, when I try to convert less the 5 series I...
23
2784
by: casper christensen | last post by:
Hi I run a directory, where programs are listed based on the number of clicks they have recieved. The program with most clicks are placed on top and so on. Now I would like people to be apple to place a link on there site so people can vote for their program, "ad a click". eg someone clicks the link on some page and it counts +1 click on my page. if some one clicks the link below it will count a click on my page.
4
2775
by: Debbiedo | last post by:
My software program outputs an XML Driving Directions file that I need to input into an Access table (although if need be I can import a dbf or xls) so that I can relate one of the fields (fromStop) and its associated driving directions back to a relational database. I have asked my software vendor for solutions but thus far they have not come up with anything. I am totally unfamiliar with XML so I am struggling with how to do this. I have...
1
1752
by: upstart | last post by:
Hi everyone…this is a tough one. You guys have been such a help before, hopefully you can point me in the right direction now. I have a Report I am working on that uses a stored procedure to pass along all off the parameters to the reporting generator (Crystal Reports) and I was currently trying to optimize it for my users, but am not sure of the best way to go about doing it. It took me forever to get it to work as it is now. I...
2
3071
by: thuythu | last post by:
Please help me.... I used and Javascript to view the data. But when i click button open a popup windows, then select data and click save button. The popup close and return the main page, but the textbox value in the main page is undefined ---------------------------------------- here are code main page: ------------------------------------------- <script language="JavaScript"> var thedata; var newwin; var thenumber; function...
0
8395
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8310
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6166
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4306
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.