[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

Question
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

7.8

How can my WCF service get a client's IP address?

Asked by ehensens in Web Services and WCF, C# Programming Language

Tags: WCF, C#

I have a WCF service that accepts HTTP POSTs and saves the payloads as xml files. How can I grab the client's IP address? Here is my WCF code:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
/* HTTP POST Payload Receiver WCF Web Service written by Erik Hensens
 * This executible server accepts the text payload of an HTTP POST
 * and saves it as a uniquely dated XML file */
 
/* To properly run this program in Windows Vista, all firewalls including
 * Windows Firewall needs to be configured to allow communication through
 * the desired port or completely disabled.
 *
 * In addition, the application must be opened by right-clicking and
 * selecting "Run as administrator" 
 * 
 * Please see Readme.txt */
 
 
 
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Xml;
 
public class getString
{
    [ServiceContract]  
    public interface IService
    {
        [OperationContract]
        [WebInvoke]
        void SaveString(Stream stream);  
    }  
 
        public class Service : IService  
        {  
            public void SaveString(Stream text)
            {
                /* stringText is POST payload stream converted to type string */
                StreamReader streamReader = new StreamReader(text);
                string stringText = streamReader.ReadToEnd().Replace('*', '\n'); ;
                streamReader.Dispose();
                
                string currentTime = DateTime.Now.ToString();
                logData("\n" + currentTime + ": Request received");
 
                string currentTimeFormatted = DateTime.Now.ToString().Replace('/', '-').Replace(' ', '_').Replace(':', '_');
                string currentFileName = "POSTPayload_" + currentTimeFormatted + ".xml";
                string currentDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string desiredXmlFolder = "XMLResults";
 
                string fileHeaderMessage = "<!-- File auto-generated at: " + currentTime + " -->";
 
                StreamWriter streamWriter = new StreamWriter(desiredXmlFolder + "\\" + currentFileName);
                streamWriter.WriteLine(fileHeaderMessage + "\n\n" + stringText);
                streamWriter.Close();
 
                int currentFileSize = stringText.Length + fileHeaderMessage.Length + 4;
                logData("HTTP POST payload saved as file:\nName: " + currentFileName + "\nDirectory: " + (currentDirectory + "\\" + desiredXmlFolder) + "\nExpected File Size: " + currentFileSize + " bytes");
 
                /* Get parameter values */
                int parameterID = getParameterID(stringText);
                int ParameterSpec;
                int ParameterHighRange;
                int ParameterLowRange;
 
                switch (parameterID)
                {
                    case 1:
                        ParameterSpec = 5;
                        ParameterHighRange = 50;
                        ParameterLowRange = 1;
                        break;
                    case 3:
                        ParameterSpec = 20;
                        ParameterHighRange = 30;
                        ParameterLowRange = 10;
                        break;
                    case 4:
                        ParameterSpec = 100;
                        ParameterHighRange = 50;
                        ParameterLowRange = 150;
                        break;
                    case 6:
                        ParameterSpec = 0;
                        ParameterHighRange = -50;
                        ParameterLowRange = 50;
                        break;
                    default:
                        ParameterSpec = -1;
                        ParameterHighRange = -1;
                        ParameterLowRange = -1;
                        break;
                }
 
                Console.WriteLine("\n\n{0}\n{1}\n{2}\n\n", ParameterSpec, ParameterHighRange, ParameterLowRange);
 
                Console.WriteLine("\n\n\nService running...\nPress <ENTER> To Exit\n\n");
            }  
        }
 
    static Binding GetBinding()  
    {
        BasicHttpBinding binding = new BasicHttpBinding()
        {
            TransferMode = TransferMode.StreamedRequest
        };
        binding.MaxReceivedMessageSize = 10000000;
        binding.MaxBufferSize = 10000000;
        return binding;
    }
 
    /* Write data on console and save it in log file */
    public static void logData(string incomingData)
    {
        StreamWriter logDataSW = File.AppendText("log.txt");
        logDataSW.WriteLine(incomingData);
        logDataSW.Close();
        Console.WriteLine(incomingData);
    }
 
    /* Get the POST payload's parameter ID */
    public static int getParameterID(string stringText)
    {
        /* Find the stringText indeces of <P> </P> */
        for (int payloadIndex = 0; payloadIndex < stringText.Length; payloadIndex++)
        {
            /* If <P> is found */
            if (stringText[payloadIndex] == '<' && stringText[payloadIndex + 1] == 'P' && stringText[payloadIndex + 2] == '>')
            {
                char paramIDchar = stringText[payloadIndex + 3];
 
                /* (int)paramIDchar will be the ASCII value, so subtract 48, the ASCII of '0' */
                return (int)paramIDchar - 48;
            }
 
            /* If <P> is not found (fatal error) */
            if (payloadIndex == stringText.Length)
            {
                Console.WriteLine("\n\nFatal error: Payload does not contain <P> indicator\n\n");
                Environment.Exit(1);
            }
        }
        return 0;
    }
 
    public static void Main()
    {
        //string baseAddress = "http://10.2.2.61:8004/Service";
        string baseAddress;
        string ipv4;
        string port;
        string directory;
 
        /* If either data.txt or log.txt does not exist, create it */
        if (!File.Exists("data.txt"))
        {
            StreamWriter tempDataSW = File.CreateText("data.txt");
            tempDataSW.Close();
        }
        if (!File.Exists("log.txt"))
        {
            StreamWriter tempLogSW = File.CreateText("log.txt");
            tempLogSW.Close();
        }
 
        /* Set Read-only to false for writeable text files */
        FileInfo dataInfo = new FileInfo("data.txt");
        FileInfo logInfo = new FileInfo("log.txt");
        dataInfo.IsReadOnly = false;
        logInfo.IsReadOnly = false;
 
        /* Load the default baseAddress to use */
        StreamReader defaultBaseSR = File.OpenText("data.txt");
        baseAddress = defaultBaseSR.ReadLine();
        defaultBaseSR.Close();
        
        Console.WriteLine("HTTP POST Payload Receiver\nWCF Web Service\n");
        
        /* If this is the very first run, get the default baseAddress to use */
        if (baseAddress == null)
        {
            Console.WriteLine("\nEnter IPv4 Address Information:\n");
            Console.WriteLine("\nUSEAGE:    http://<IPv4>:<Port>/<Directory>\n\nNOTE: User should enter \"Service\" for Directory\n");
            Console.Write("\nIPv4:      ");
            ipv4 = Console.ReadLine();
            Console.Write("Port:      ");
            port = Console.ReadLine();
            Console.Write("Directory: ");
            directory = Console.ReadLine();
            baseAddress = "http://" + ipv4 + ":" + port + "/" + directory;
            Console.Write("\n");
 
            StreamWriter firstTimeAddressSW = File.AppendText("data.txt");
            firstTimeAddressSW.WriteLine(baseAddress);
            firstTimeAddressSW.Close();
        }
 
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
 
        Console.WriteLine("Default Web Host: {0}\n", baseAddress);
        Console.WriteLine("\nMenu\n\n1 - Modify Web Host\n2 - Exit\nPress <ENTER> To Run\n");
 
        string userChoice = Console.ReadLine();
        if (userChoice == "1")
        {
            Console.WriteLine("\nUSEAGE:    http://<IPv4>:<Port>/<Directory>\n\nNOTE: User should enter \"Service\" for Directory\n");
            Console.Write("\nIPv4:      ");
            ipv4 = Console.ReadLine();
            Console.Write("Port:      ");
            port = Console.ReadLine();
            Console.Write("Directory: ");
            directory = Console.ReadLine();
            baseAddress = "http://" + ipv4 + ":" + port + "/" + directory;
            Console.Write("\n");
            
            /* Re-write default baseAddress */
            StreamWriter rewriteAddressSW = new StreamWriter("data.txt");
            rewriteAddressSW.Write(baseAddress);
            rewriteAddressSW.Close();
            Console.WriteLine("Program will now need to restart...\n");
            Console.ReadLine();
            Environment.Exit(1);
 
        }
        else if (userChoice == "2")
            Environment.Exit(1);
        else { }
 
        Console.WriteLine("Web Host: {0}\n", baseAddress);
 
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "text/plain";
        Console.WriteLine("Service running...\nPress <ENTER> To Exit\n");
        Console.ReadLine();
        host.Close();
    }
}
 
Related Solutions
Keywords: How can my WCF service get a client…
 
Loading Advertisement...
 
[+][-]03/02/09 12:09 PM, ID: 23777673Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]03/03/09 07:10 AM, ID: 23784448Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]03/03/09 08:13 AM, ID: 23785178Accepted Solution

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

About this solution

Zones: Web Services and WCF, C# Programming Language
Tags: WCF, C#
Sign Up Now!
Solution Provided By: ehensens
Participating Experts: 2
Solution Grade: A
 
[+][-]03/04/09 12:47 PM, ID: 23799291Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]03/05/09 07:28 AM, ID: 23806446Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091111-EE-VQP-89 - Hierarchy / EE_QW_3_20080625